@myrialabs/clopen 0.4.39 → 0.4.40
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/backend/auth/permissions.ts +23 -0
- package/backend/database/crypto/secret-columns.ts +5 -1
- package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +6 -0
- package/backend/database/queries/worktree-branch-queries.ts +331 -0
- package/backend/db-client/cloning.test.ts +161 -0
- package/backend/db-client/cloning.ts +672 -0
- package/backend/db-client/connection-url.test.ts +117 -0
- package/backend/db-client/connection-url.ts +126 -0
- package/backend/db-client/drivers/mongodb.ts +2 -14
- package/backend/db-client/drivers/mysql.ts +2 -8
- package/backend/db-client/drivers/postgres.ts +10 -13
- package/backend/db-client/drivers/redis.ts +2 -6
- package/backend/db-client/env/detect.ts +438 -0
- package/backend/db-client/env/diff.ts +94 -0
- package/backend/db-client/env/env.test.ts +574 -0
- package/backend/db-client/env/index.ts +15 -0
- package/backend/db-client/env/naming.ts +202 -0
- package/backend/db-client/env/service.ts +487 -0
- package/backend/db-client/integrations/index.ts +7 -0
- package/backend/db-client/integrations/links.ts +41 -10
- package/backend/db-client/providers/neon/adapter.ts +522 -0
- package/backend/db-client/providers/neon/api-types.ts +182 -0
- package/backend/db-client/providers/neon/client.ts +298 -0
- package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
- package/backend/db-client/providers/neon/endpoints.ts +314 -0
- package/backend/db-client/providers/neon/list.test.ts +181 -0
- package/backend/db-client/providers/supabase/adapter.ts +25 -2
- package/backend/db-client/providers/types.ts +57 -0
- package/backend/env-files/discovery.ts +48 -0
- package/backend/env-files/edit.ts +213 -0
- package/backend/env-files/env-files.test.ts +515 -0
- package/backend/env-files/git.ts +27 -0
- package/backend/env-files/index.ts +44 -0
- package/backend/env-files/keys.ts +69 -0
- package/backend/env-files/parse.ts +157 -0
- package/backend/env-files/write.ts +229 -0
- package/backend/integrations/health.ts +18 -4
- package/backend/integrations/projections/types.ts +9 -2
- package/backend/integrations/registry/index.ts +3 -0
- package/backend/integrations/registry/providers/context7.ts +1 -0
- package/backend/integrations/registry/providers/firecrawl.ts +1 -0
- package/backend/integrations/registry/providers/github.ts +1 -0
- package/backend/integrations/registry/providers/neon.ts +55 -0
- package/backend/integrations/registry/providers/supabase.ts +1 -0
- package/backend/integrations/registry/providers/vercel.ts +1 -0
- package/backend/integrations/registry/types.ts +2 -0
- package/backend/work/start-work.ts +4 -0
- package/backend/worktrees/branching/engine.ts +557 -0
- package/backend/worktrees/branching/index.ts +56 -0
- package/backend/worktrees/branching/naming.test.ts +118 -0
- package/backend/worktrees/branching/naming.ts +97 -0
- package/backend/worktrees/branching/projector.test.ts +229 -0
- package/backend/worktrees/branching/projector.ts +139 -0
- package/backend/worktrees/branching/providers/neon.ts +220 -0
- package/backend/worktrees/branching/registry.ts +27 -0
- package/backend/worktrees/branching/service.ts +620 -0
- package/backend/worktrees/branching/suggest.test.ts +154 -0
- package/backend/worktrees/branching/suggest.ts +202 -0
- package/backend/worktrees/branching/types.ts +88 -0
- package/backend/worktrees/index.ts +7 -0
- package/backend/worktrees/service.ts +48 -1
- package/backend/ws/db-client/env.ts +142 -0
- package/backend/ws/db-client/index.ts +2 -0
- package/backend/ws/projects/index.ts +6 -1
- package/backend/ws/projects/info.ts +70 -6
- package/backend/ws/projects/overview.test.ts +108 -0
- package/backend/ws/projects/overview.ts +300 -0
- package/backend/ws/system/device-info.ts +307 -76
- package/backend/ws/worktrees/branching.ts +212 -0
- package/backend/ws/worktrees/crud.ts +33 -7
- package/backend/ws/worktrees/index.ts +14 -0
- package/dist/assets/{index-C8Gi-b6U.js → index-D4igjF6e.js} +1 -1
- package/dist/assets/{index-BrF6nqld.js → index-DONNwiXm.js} +1 -1
- package/dist/assets/main-BrfXH1bL.js +1205 -0
- package/dist/assets/main-CT1PygsW.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/constants/tool-icons.ts +6 -2
- package/shared/types/db-client/env.ts +192 -0
- package/shared/types/db-client/index.ts +1 -0
- package/shared/types/db-client/integrations.ts +30 -0
- package/shared/types/integrations.ts +9 -0
- package/shared/types/worktree-branching.ts +315 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-Bd3gb79F.css +0 -1
- package/dist/assets/main-Bo1hD7mt.js +0 -1191
|
@@ -0,0 +1,672 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copying a database, using whatever the server itself can do.
|
|
3
|
+
*
|
|
4
|
+
* This is what makes "give this worktree its own database" a property of every
|
|
5
|
+
* database Clopen can reach, rather than of the one provider that happens to
|
|
6
|
+
* sell branching. Neon cuts a copy-on-write branch through its API; everything
|
|
7
|
+
* else gets a sibling database on the same server, made with that engine's own
|
|
8
|
+
* primitives.
|
|
9
|
+
*
|
|
10
|
+
* NO EXTERNAL CLI. Not `pg_dump`, not `mysqldump`, not `mongodump`. Clopen ships
|
|
11
|
+
* to Linux, macOS and Windows and installs no database tooling, so a strategy
|
|
12
|
+
* that shells out is one that works on the maintainer's machine and nowhere
|
|
13
|
+
* else. Everything below is SQL or a driver command.
|
|
14
|
+
*
|
|
15
|
+
* FIDELITY IS REPORTED, NEVER ASSUMED. The strategies differ in what they carry:
|
|
16
|
+
* Postgres's `TEMPLATE` copies a database whole, while a table-by-table copy
|
|
17
|
+
* carries structure and rows and leaves foreign keys, triggers, views and
|
|
18
|
+
* routines behind. That difference decides whether a migration an agent runs in
|
|
19
|
+
* a worktree will also work on main, so every result says which strategy ran
|
|
20
|
+
* and what it did not bring.
|
|
21
|
+
*
|
|
22
|
+
* TRANSIENT CONNECTIONS, not the pooled one, wherever the work is per-database.
|
|
23
|
+
* Two reasons, both of which bit first: Postgres refuses `CREATE DATABASE …
|
|
24
|
+
* TEMPLATE` while ANY session is connected to the template — including Clopen's
|
|
25
|
+
* own pool — and the Redis adapter holds a single client whose logical database
|
|
26
|
+
* comes from its URL, so a `SELECT 3` issued on it would silently move every
|
|
27
|
+
* other query in the panel.
|
|
28
|
+
*
|
|
29
|
+
* Reused rather than owned: this is a DB Client capability — "copy a database" —
|
|
30
|
+
* and worktree branching is its first caller.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import type {
|
|
34
|
+
DbClientConnection,
|
|
35
|
+
DbClientConnectionInput,
|
|
36
|
+
DbClientQueryResult,
|
|
37
|
+
DbDriver
|
|
38
|
+
} from '$shared/types/db-client';
|
|
39
|
+
import { connectionManager } from './connection-manager';
|
|
40
|
+
import type { DbClientDriverAdapter } from './drivers/types';
|
|
41
|
+
import { assertSafeIdentifier, quoteMssql, quoteMysql, quotePg } from './drivers/sql-builders';
|
|
42
|
+
import { debug } from '$shared/utils/logger';
|
|
43
|
+
|
|
44
|
+
/** How much of the parent comes across. */
|
|
45
|
+
export type DbCloneMode = 'schema-data' | 'schema' | 'empty';
|
|
46
|
+
|
|
47
|
+
/** Which mechanism actually ran, for the sentence shown afterwards. */
|
|
48
|
+
export type DbCloneStrategy =
|
|
49
|
+
| 'template'
|
|
50
|
+
| 'server-copy'
|
|
51
|
+
| 'row-copy'
|
|
52
|
+
| 'file-copy'
|
|
53
|
+
| 'logical-db'
|
|
54
|
+
| 'empty';
|
|
55
|
+
|
|
56
|
+
export interface DbCloneResult {
|
|
57
|
+
/** The new database's name, its file path for SQLite, its index for Redis. */
|
|
58
|
+
database: string;
|
|
59
|
+
strategy: DbCloneStrategy;
|
|
60
|
+
/** One sentence naming what did not come across, or null when nothing did not. */
|
|
61
|
+
notice: string | null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** What copying can do for a driver, before anything is attempted. */
|
|
65
|
+
export interface DbCloneSupport {
|
|
66
|
+
canClone: boolean;
|
|
67
|
+
/** One sentence naming the limit, shown BEFORE the user commits to it. */
|
|
68
|
+
notice: string | null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Rows moved per round trip when a copy has to go through Clopen. */
|
|
72
|
+
const ROW_BATCH = 500;
|
|
73
|
+
|
|
74
|
+
/** What a table-by-table copy cannot carry, said once. */
|
|
75
|
+
const PARTIAL_COPY_NOTICE =
|
|
76
|
+
'Copied table by table, so foreign keys, triggers, views and routines do not come across.';
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* SQL Server's is worse, and says so.
|
|
80
|
+
*
|
|
81
|
+
* `SELECT … INTO` builds the destination table from the shape of the result
|
|
82
|
+
* set, which is columns and nothing else — so indexes, keys and defaults are
|
|
83
|
+
* missing on top of everything `PARTIAL_COPY_NOTICE` already lists.
|
|
84
|
+
*/
|
|
85
|
+
const MSSQL_COPY_NOTICE =
|
|
86
|
+
'Copied table by table, so indexes, keys, defaults and routines do not come across.';
|
|
87
|
+
|
|
88
|
+
export function cloneSupport(driver: DbDriver): DbCloneSupport {
|
|
89
|
+
switch (driver) {
|
|
90
|
+
case 'postgres':
|
|
91
|
+
// The faithful path needs exclusive access to the parent and the
|
|
92
|
+
// fallback is always available, so the capability never disappears and
|
|
93
|
+
// there is nothing to warn about up front.
|
|
94
|
+
return { canClone: true, notice: null };
|
|
95
|
+
case 'mysql':
|
|
96
|
+
return { canClone: true, notice: PARTIAL_COPY_NOTICE };
|
|
97
|
+
case 'mssql':
|
|
98
|
+
return { canClone: true, notice: MSSQL_COPY_NOTICE };
|
|
99
|
+
case 'sqlite':
|
|
100
|
+
return { canClone: true, notice: null };
|
|
101
|
+
case 'mongodb':
|
|
102
|
+
return {
|
|
103
|
+
canClone: true,
|
|
104
|
+
notice: 'Collections and their indexes are copied; validators and views are not.'
|
|
105
|
+
};
|
|
106
|
+
case 'redis':
|
|
107
|
+
return {
|
|
108
|
+
canClone: true,
|
|
109
|
+
notice:
|
|
110
|
+
'A Redis copy is another logical database on the same server, so the two share memory and eviction.'
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Whether this connection could be a branch parent at all. */
|
|
116
|
+
export function canBranchFrom(connection: DbClientConnection): boolean {
|
|
117
|
+
if (!cloneSupport(connection.driver).canClone) return false;
|
|
118
|
+
// An SSH tunnel belongs to Clopen's own process, so a copy made through one
|
|
119
|
+
// is reachable from Clopen and from nowhere the project runs.
|
|
120
|
+
return !connection.ssh?.enabled;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function messageOf(error: unknown): string {
|
|
124
|
+
return error instanceof Error ? error.message : String(error);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* A connection of our own, pointed wherever this step needs to be.
|
|
129
|
+
*
|
|
130
|
+
* Always closed, including on failure: a leaked adapter holds a session, and a
|
|
131
|
+
* held session is the exact thing that makes the next `CREATE DATABASE …
|
|
132
|
+
* TEMPLATE` fall back to the slow path.
|
|
133
|
+
*/
|
|
134
|
+
async function withTransient<T>(
|
|
135
|
+
connection: DbClientConnection,
|
|
136
|
+
database: string | null,
|
|
137
|
+
run: (adapter: DbClientDriverAdapter) => Promise<T>
|
|
138
|
+
): Promise<T> {
|
|
139
|
+
const input: DbClientConnectionInput = {
|
|
140
|
+
name: connection.name,
|
|
141
|
+
driver: connection.driver,
|
|
142
|
+
host: connection.host ?? undefined,
|
|
143
|
+
port: connection.port ?? undefined,
|
|
144
|
+
username: connection.username ?? undefined,
|
|
145
|
+
password: connection.password ?? undefined,
|
|
146
|
+
database: database ?? connection.database ?? undefined,
|
|
147
|
+
sslMode: connection.sslMode,
|
|
148
|
+
sslCa: connection.sslCa ?? undefined,
|
|
149
|
+
options: connection.options
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const { adapter, tunnel } = await connectionManager.openTransient(input);
|
|
153
|
+
try {
|
|
154
|
+
return await run(adapter);
|
|
155
|
+
} finally {
|
|
156
|
+
await adapter.close().catch((error) => {
|
|
157
|
+
debug.warn('db-client', `Transient adapter close failed: ${messageOf(error)}`);
|
|
158
|
+
});
|
|
159
|
+
await tunnel?.close().catch((error) => {
|
|
160
|
+
debug.warn('db-client', `Transient tunnel close failed: ${messageOf(error)}`);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function read(
|
|
166
|
+
adapter: DbClientDriverAdapter,
|
|
167
|
+
sql: string,
|
|
168
|
+
database?: string
|
|
169
|
+
): Promise<DbClientQueryResult> {
|
|
170
|
+
if (!adapter.executeRead) throw new Error('This connection cannot run queries.');
|
|
171
|
+
return adapter.executeRead(sql, [], { database, limit: 1_000_000 });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function write(
|
|
175
|
+
adapter: DbClientDriverAdapter,
|
|
176
|
+
sql: string,
|
|
177
|
+
database?: string
|
|
178
|
+
): Promise<void> {
|
|
179
|
+
if (!adapter.executeWrite) throw new Error('This connection cannot run statements.');
|
|
180
|
+
await adapter.executeWrite(sql, [], { database });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Every database on the server, as plain names. */
|
|
184
|
+
export async function listDatabaseNames(connectionId: string): Promise<string[]> {
|
|
185
|
+
const adapter = await connectionManager.get(connectionId);
|
|
186
|
+
if (!adapter.listDatabases) return [];
|
|
187
|
+
return (await adapter.listDatabases()).map((node) => node.name);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Copy one database into a new one beside it.
|
|
192
|
+
*
|
|
193
|
+
* The caller passes the saved connection rather than its id because most of
|
|
194
|
+
* this work happens on connections of our own — see the module note.
|
|
195
|
+
*/
|
|
196
|
+
export async function cloneDatabase(input: {
|
|
197
|
+
connection: DbClientConnection;
|
|
198
|
+
/** The database to copy. A file path for SQLite, an index for Redis. */
|
|
199
|
+
source: string;
|
|
200
|
+
/** The name to create. A file path for SQLite, an index for Redis. */
|
|
201
|
+
target: string;
|
|
202
|
+
mode: DbCloneMode;
|
|
203
|
+
}): Promise<DbCloneResult> {
|
|
204
|
+
// Let go of the pooled session first. For Postgres it is what decides which
|
|
205
|
+
// strategy is even available; for SQLite it is what makes the file safe to
|
|
206
|
+
// copy; everywhere else it costs one reconnect.
|
|
207
|
+
await connectionManager.release(input.connection.id);
|
|
208
|
+
|
|
209
|
+
switch (input.connection.driver) {
|
|
210
|
+
case 'postgres':
|
|
211
|
+
return clonePostgres(input);
|
|
212
|
+
case 'mysql':
|
|
213
|
+
return cloneMysql(input);
|
|
214
|
+
case 'mssql':
|
|
215
|
+
return cloneMssql(input);
|
|
216
|
+
case 'mongodb':
|
|
217
|
+
return cloneMongo(input);
|
|
218
|
+
case 'redis':
|
|
219
|
+
return cloneRedis(input);
|
|
220
|
+
case 'sqlite':
|
|
221
|
+
return cloneSqlite(input);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Drop a copy.
|
|
227
|
+
*
|
|
228
|
+
* Never the parent: every path here is given the copy's own name, and the
|
|
229
|
+
* callers get that name from the row that recorded the copy rather than from
|
|
230
|
+
* anything a user typed.
|
|
231
|
+
*/
|
|
232
|
+
export async function dropClonedDatabase(input: {
|
|
233
|
+
connection: DbClientConnection;
|
|
234
|
+
database: string;
|
|
235
|
+
}): Promise<void> {
|
|
236
|
+
await connectionManager.release(input.connection.id);
|
|
237
|
+
const driver = input.connection.driver;
|
|
238
|
+
|
|
239
|
+
if (driver === 'sqlite') {
|
|
240
|
+
const fs = await import('fs/promises');
|
|
241
|
+
// The journal files are part of the database, not debris beside it.
|
|
242
|
+
for (const suffix of ['', '-wal', '-shm']) {
|
|
243
|
+
await fs.rm(`${input.database}${suffix}`, { force: true });
|
|
244
|
+
}
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (driver === 'redis') {
|
|
249
|
+
await withTransient(input.connection, input.database, async (adapter) => {
|
|
250
|
+
await write(adapter, 'FLUSHDB');
|
|
251
|
+
});
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (driver === 'mongodb') {
|
|
256
|
+
// The command layer addresses COLLECTIONS, so there is no `dropDatabase`
|
|
257
|
+
// to call — and a Mongo database with no collections is a Mongo database
|
|
258
|
+
// that no longer exists in any way a user can see.
|
|
259
|
+
await withTransient(input.connection, input.database, async (adapter) => {
|
|
260
|
+
for (const name of await collectionNames(adapter, input.database)) {
|
|
261
|
+
await write(adapter, mongoCommand(name, 'drop'), input.database);
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
assertSafeIdentifier(input.database);
|
|
268
|
+
const maintenance = driver === 'postgres' ? 'postgres' : null;
|
|
269
|
+
await withTransient(input.connection, maintenance, async (adapter) => {
|
|
270
|
+
if (!adapter.dropDatabase) throw new Error('This connection cannot drop databases.');
|
|
271
|
+
await adapter.dropDatabase(input.database);
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/* ---------------------------------------------------------------- postgres */
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* `CREATE DATABASE … TEMPLATE` first, table-by-table second.
|
|
279
|
+
*
|
|
280
|
+
* The template path is the only one that carries a database whole — constraints,
|
|
281
|
+
* triggers, sequences, extensions, the lot. Postgres refuses it while any other
|
|
282
|
+
* session is connected to the template, which on a machine running the
|
|
283
|
+
* project's own dev server is most of the time. So the refusal is not an error
|
|
284
|
+
* here: it is the signal to take the slower path, which is always available and
|
|
285
|
+
* costs nothing but time and the fidelity the result then reports.
|
|
286
|
+
*
|
|
287
|
+
* Terminating the blocking sessions would give the faithful copy back, and it
|
|
288
|
+
* is deliberately not done: those sessions are someone's running application.
|
|
289
|
+
*/
|
|
290
|
+
async function clonePostgres(input: {
|
|
291
|
+
connection: DbClientConnection;
|
|
292
|
+
source: string;
|
|
293
|
+
target: string;
|
|
294
|
+
mode: DbCloneMode;
|
|
295
|
+
}): Promise<DbCloneResult> {
|
|
296
|
+
assertSafeIdentifier(input.target);
|
|
297
|
+
|
|
298
|
+
return withTransient(input.connection, 'postgres', async (adapter) => {
|
|
299
|
+
if (input.mode === 'schema-data') {
|
|
300
|
+
try {
|
|
301
|
+
await write(
|
|
302
|
+
adapter,
|
|
303
|
+
`CREATE DATABASE ${quotePg(input.target)} TEMPLATE ${quotePg(input.source)}`,
|
|
304
|
+
'postgres'
|
|
305
|
+
);
|
|
306
|
+
return { database: input.target, strategy: 'template' as const, notice: null };
|
|
307
|
+
} catch (error) {
|
|
308
|
+
debug.log(
|
|
309
|
+
'db-client',
|
|
310
|
+
`Postgres TEMPLATE copy refused (${messageOf(error)}), copying table by table instead`
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
await write(adapter, `CREATE DATABASE ${quotePg(input.target)}`, 'postgres');
|
|
316
|
+
if (input.mode === 'empty') {
|
|
317
|
+
return { database: input.target, strategy: 'empty' as const, notice: null };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
await copyTablesThroughClopen(adapter, {
|
|
321
|
+
source: input.source,
|
|
322
|
+
target: input.target,
|
|
323
|
+
withData: input.mode === 'schema-data',
|
|
324
|
+
quote: quotePg
|
|
325
|
+
});
|
|
326
|
+
return {
|
|
327
|
+
database: input.target,
|
|
328
|
+
strategy: 'row-copy' as const,
|
|
329
|
+
notice: PARTIAL_COPY_NOTICE
|
|
330
|
+
};
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/* ------------------------------------------------------------------- mysql */
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Server-side, and the data never crosses the wire.
|
|
338
|
+
*
|
|
339
|
+
* MySQL addresses tables as `database.table` within one connection, so both
|
|
340
|
+
* halves of the copy are statements the server runs against its own storage.
|
|
341
|
+
* `CREATE TABLE … LIKE` carries columns and indexes; foreign keys, triggers,
|
|
342
|
+
* views and routines it does not, which is what the notice says.
|
|
343
|
+
*/
|
|
344
|
+
async function cloneMysql(input: {
|
|
345
|
+
connection: DbClientConnection;
|
|
346
|
+
source: string;
|
|
347
|
+
target: string;
|
|
348
|
+
mode: DbCloneMode;
|
|
349
|
+
}): Promise<DbCloneResult> {
|
|
350
|
+
assertSafeIdentifier(input.target);
|
|
351
|
+
|
|
352
|
+
return withTransient(input.connection, input.source, async (adapter) => {
|
|
353
|
+
await write(adapter, `CREATE DATABASE ${quoteMysql(input.target)}`);
|
|
354
|
+
if (input.mode === 'empty') {
|
|
355
|
+
return { database: input.target, strategy: 'empty' as const, notice: null };
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
for (const table of await tableNames(adapter, input.source)) {
|
|
359
|
+
const from = `${quoteMysql(input.source)}.${quoteMysql(table)}`;
|
|
360
|
+
const to = `${quoteMysql(input.target)}.${quoteMysql(table)}`;
|
|
361
|
+
await write(adapter, `CREATE TABLE ${to} LIKE ${from}`);
|
|
362
|
+
if (input.mode === 'schema-data') {
|
|
363
|
+
await write(adapter, `INSERT INTO ${to} SELECT * FROM ${from}`);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
return {
|
|
368
|
+
database: input.target,
|
|
369
|
+
strategy: 'server-copy' as const,
|
|
370
|
+
notice: PARTIAL_COPY_NOTICE
|
|
371
|
+
};
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/* ------------------------------------------------------------------- mssql */
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* `SELECT … INTO`, which creates the table and fills it in one statement.
|
|
379
|
+
*
|
|
380
|
+
* Cross-database within an instance is native here, so this is server-side like
|
|
381
|
+
* MySQL's. What `SELECT INTO` does NOT create is indexes, keys or defaults —
|
|
382
|
+
* more missing than MySQL's `LIKE`, so this one has its own sentence.
|
|
383
|
+
*/
|
|
384
|
+
async function cloneMssql(input: {
|
|
385
|
+
connection: DbClientConnection;
|
|
386
|
+
source: string;
|
|
387
|
+
target: string;
|
|
388
|
+
mode: DbCloneMode;
|
|
389
|
+
}): Promise<DbCloneResult> {
|
|
390
|
+
assertSafeIdentifier(input.target);
|
|
391
|
+
|
|
392
|
+
return withTransient(input.connection, input.source, async (adapter) => {
|
|
393
|
+
await write(adapter, `CREATE DATABASE ${quoteMssql(input.target)}`);
|
|
394
|
+
if (input.mode === 'empty') {
|
|
395
|
+
return { database: input.target, strategy: 'empty' as const, notice: null };
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
for (const table of await tableNames(adapter, input.source)) {
|
|
399
|
+
const from = `${quoteMssql(input.source)}.dbo.${quoteMssql(table)}`;
|
|
400
|
+
const to = `${quoteMssql(input.target)}.dbo.${quoteMssql(table)}`;
|
|
401
|
+
// `TOP 0` builds the table and copies no rows, which is the schema-only
|
|
402
|
+
// case expressed in the same statement rather than a second code path.
|
|
403
|
+
const top = input.mode === 'schema' ? 'TOP 0 ' : '';
|
|
404
|
+
await write(adapter, `SELECT ${top}* INTO ${to} FROM ${from}`);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
return {
|
|
408
|
+
database: input.target,
|
|
409
|
+
strategy: 'server-copy' as const,
|
|
410
|
+
notice: MSSQL_COPY_NOTICE
|
|
411
|
+
};
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/* ----------------------------------------------------------------- mongodb */
|
|
416
|
+
|
|
417
|
+
/** The command shape this driver parses: a collection, an op, and its args. */
|
|
418
|
+
function mongoCommand(collection: string, op: string, args: unknown[] = []): string {
|
|
419
|
+
return JSON.stringify({ collection, op, args });
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* `$out` into the new database, which the server performs itself.
|
|
424
|
+
*
|
|
425
|
+
* Indexes are re-created afterwards, because `$out` writes a collection and
|
|
426
|
+
* nothing else — and an index-less copy of a large collection is a worktree
|
|
427
|
+
* where every query is a scan.
|
|
428
|
+
*/
|
|
429
|
+
async function cloneMongo(input: {
|
|
430
|
+
connection: DbClientConnection;
|
|
431
|
+
source: string;
|
|
432
|
+
target: string;
|
|
433
|
+
mode: DbCloneMode;
|
|
434
|
+
}): Promise<DbCloneResult> {
|
|
435
|
+
if (input.mode === 'empty') {
|
|
436
|
+
// Mongo creates a database on its first write, so there is nothing to do
|
|
437
|
+
// here and nothing to pretend about.
|
|
438
|
+
return { database: input.target, strategy: 'empty', notice: null };
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
return withTransient(input.connection, input.source, async (adapter) => {
|
|
442
|
+
for (const name of await collectionNames(adapter, input.source)) {
|
|
443
|
+
// `$limit: 0` is the schema-only case: the pipeline still runs and
|
|
444
|
+
// `$out` still creates the collection, with nothing in it.
|
|
445
|
+
const pipeline = input.mode === 'schema' ? [{ $limit: 0 }] : [];
|
|
446
|
+
await write(
|
|
447
|
+
adapter,
|
|
448
|
+
mongoCommand(name, 'aggregate', [
|
|
449
|
+
[...pipeline, { $out: { db: input.target, coll: name } }]
|
|
450
|
+
]),
|
|
451
|
+
input.source
|
|
452
|
+
);
|
|
453
|
+
|
|
454
|
+
try {
|
|
455
|
+
const found = await read(adapter, mongoCommand(name, 'indexes'), input.source);
|
|
456
|
+
const specs = found.rows
|
|
457
|
+
.filter((row) => row.name !== '_id_')
|
|
458
|
+
.map((row) => ({ key: row.key, name: row.name, unique: row.unique === true }));
|
|
459
|
+
if (specs.length > 0) {
|
|
460
|
+
await write(adapter, mongoCommand(name, 'createIndexes', [specs]), input.target);
|
|
461
|
+
}
|
|
462
|
+
} catch (error) {
|
|
463
|
+
// An index that could not be re-created costs performance, not
|
|
464
|
+
// correctness, so it is logged rather than failing the whole copy.
|
|
465
|
+
debug.warn('db-client', `Could not copy indexes for ${name}: ${messageOf(error)}`);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
return {
|
|
470
|
+
database: input.target,
|
|
471
|
+
strategy: 'server-copy' as const,
|
|
472
|
+
notice: cloneSupport('mongodb').notice
|
|
473
|
+
};
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/* ------------------------------------------------------------------- redis */
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* Another logical database on the same server.
|
|
481
|
+
*
|
|
482
|
+
* Redis has no second database to create — it has numbered ones, and a copy is
|
|
483
|
+
* keys moved into a free index with `COPY … DB n`. Which index is free is a
|
|
484
|
+
* question about the server, so the caller picks it and passes it as `target`.
|
|
485
|
+
*
|
|
486
|
+
* Both halves run on CONNECTIONS OF OUR OWN, one per index. The panel's adapter
|
|
487
|
+
* holds a single client whose index came from its URL, and a `SELECT` on it
|
|
488
|
+
* would move every other query in DB Client without anything saying so.
|
|
489
|
+
*/
|
|
490
|
+
async function cloneRedis(input: {
|
|
491
|
+
connection: DbClientConnection;
|
|
492
|
+
source: string;
|
|
493
|
+
target: string;
|
|
494
|
+
mode: DbCloneMode;
|
|
495
|
+
}): Promise<DbCloneResult> {
|
|
496
|
+
const index = Number(input.target);
|
|
497
|
+
if (!Number.isInteger(index) || index < 0) {
|
|
498
|
+
throw new Error(`"${input.target}" is not a Redis database index.`);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
await withTransient(input.connection, input.target, async (adapter) => {
|
|
502
|
+
await write(adapter, 'FLUSHDB');
|
|
503
|
+
});
|
|
504
|
+
|
|
505
|
+
// Redis has no schema, so "schema only" and "empty" describe the same
|
|
506
|
+
// database and pretending otherwise would be inventing a distinction.
|
|
507
|
+
if (input.mode !== 'schema-data') {
|
|
508
|
+
return { database: input.target, strategy: 'empty', notice: null };
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const copied = await withTransient(input.connection, input.source, async (adapter) => {
|
|
512
|
+
let cursor = '0';
|
|
513
|
+
let count = 0;
|
|
514
|
+
do {
|
|
515
|
+
const scan = await read(adapter, `SCAN ${cursor} COUNT 500`);
|
|
516
|
+
const row = (scan.rows[0] ?? {}) as Record<string, unknown>;
|
|
517
|
+
cursor = String(row.cursor ?? '0');
|
|
518
|
+
const keys = Array.isArray(row.keys) ? (row.keys as string[]) : [];
|
|
519
|
+
for (const key of keys) {
|
|
520
|
+
await write(adapter, `COPY ${JSON.stringify(key)} ${JSON.stringify(key)} DB ${index} REPLACE`);
|
|
521
|
+
count += 1;
|
|
522
|
+
}
|
|
523
|
+
} while (cursor !== '0');
|
|
524
|
+
return count;
|
|
525
|
+
});
|
|
526
|
+
|
|
527
|
+
debug.log('db-client', `Copied ${copied} Redis key(s) into database ${index}`);
|
|
528
|
+
return { database: input.target, strategy: 'logical-db', notice: cloneSupport('redis').notice };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/* ------------------------------------------------------------------ sqlite */
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Copy the file, which IS the whole database.
|
|
535
|
+
*
|
|
536
|
+
* The most literal strategy here and the most faithful: everything the other
|
|
537
|
+
* paths have to apologise for comes across, because none of it is being
|
|
538
|
+
* re-created. The `-wal` and `-shm` files come too — a copy without them can be
|
|
539
|
+
* missing committed transactions.
|
|
540
|
+
*/
|
|
541
|
+
async function cloneSqlite(input: {
|
|
542
|
+
source: string;
|
|
543
|
+
target: string;
|
|
544
|
+
mode: DbCloneMode;
|
|
545
|
+
}): Promise<DbCloneResult> {
|
|
546
|
+
const fs = await import('fs/promises');
|
|
547
|
+
|
|
548
|
+
if (input.mode === 'empty') {
|
|
549
|
+
await fs.writeFile(input.target, '');
|
|
550
|
+
return { database: input.target, strategy: 'empty', notice: null };
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
await fs.copyFile(input.source, input.target);
|
|
554
|
+
for (const suffix of ['-wal', '-shm']) {
|
|
555
|
+
try {
|
|
556
|
+
await fs.copyFile(`${input.source}${suffix}`, `${input.target}${suffix}`);
|
|
557
|
+
} catch {
|
|
558
|
+
// Absent in the ordinary case: a database not in WAL mode has neither.
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
if (input.mode === 'schema') {
|
|
563
|
+
// Emptying the COPY is safe in a way emptying the original never would be,
|
|
564
|
+
// and it is the only route from a file copy to schema-without-data.
|
|
565
|
+
const { Database } = await import('bun:sqlite');
|
|
566
|
+
const db = new Database(input.target);
|
|
567
|
+
try {
|
|
568
|
+
const tables = db
|
|
569
|
+
.query(`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
|
|
570
|
+
.all() as { name: string }[];
|
|
571
|
+
for (const table of tables) db.run(`DELETE FROM "${table.name.replace(/"/g, '""')}"`);
|
|
572
|
+
} finally {
|
|
573
|
+
db.close();
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
return { database: input.target, strategy: 'file-copy', notice: null };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/* ------------------------------------------------------------------ shared */
|
|
581
|
+
|
|
582
|
+
async function tableNames(adapter: DbClientDriverAdapter, database: string): Promise<string[]> {
|
|
583
|
+
if (!adapter.listObjects) throw new Error('This connection cannot list tables.');
|
|
584
|
+
const nodes = await adapter.listObjects(database);
|
|
585
|
+
return nodes.filter((node) => node.type === 'table').map((node) => node.name);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
async function collectionNames(
|
|
589
|
+
adapter: DbClientDriverAdapter,
|
|
590
|
+
database: string
|
|
591
|
+
): Promise<string[]> {
|
|
592
|
+
if (!adapter.listObjects) throw new Error('This connection cannot list collections.');
|
|
593
|
+
const nodes = await adapter.listObjects(database);
|
|
594
|
+
return nodes.filter((node) => node.type === 'collection').map((node) => node.name);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* Structure and rows, one table at a time, through Clopen.
|
|
599
|
+
*
|
|
600
|
+
* The fallback of last resort for Postgres, where cross-database SQL does not
|
|
601
|
+
* exist: every row is read into this process and written back out. Slow and
|
|
602
|
+
* memory-hungry next to anything the server does itself, which is why it is a
|
|
603
|
+
* fallback — but it needs no permission the user does not already have and no
|
|
604
|
+
* tool they have not already installed.
|
|
605
|
+
*/
|
|
606
|
+
async function copyTablesThroughClopen(
|
|
607
|
+
adapter: DbClientDriverAdapter,
|
|
608
|
+
input: {
|
|
609
|
+
source: string;
|
|
610
|
+
target: string;
|
|
611
|
+
withData: boolean;
|
|
612
|
+
quote: (name: string) => string;
|
|
613
|
+
}
|
|
614
|
+
): Promise<void> {
|
|
615
|
+
const quote = input.quote;
|
|
616
|
+
|
|
617
|
+
for (const table of await tableNames(adapter, input.source)) {
|
|
618
|
+
if (!adapter.getObjectDetails) throw new Error('This connection cannot describe tables.');
|
|
619
|
+
|
|
620
|
+
const details = await adapter.getObjectDetails(table, 'table', input.source);
|
|
621
|
+
const columns = details.columns ?? [];
|
|
622
|
+
if (columns.length === 0) continue;
|
|
623
|
+
|
|
624
|
+
const lines = columns.map((column) => {
|
|
625
|
+
const parts = [quote(column.name), column.type];
|
|
626
|
+
if (!column.nullable) parts.push('NOT NULL');
|
|
627
|
+
if (column.default !== null && column.default !== undefined && column.default !== '') {
|
|
628
|
+
parts.push(`DEFAULT ${column.default}`);
|
|
629
|
+
}
|
|
630
|
+
if (column.isPrimary) parts.push('PRIMARY KEY');
|
|
631
|
+
else if (column.isUnique) parts.push('UNIQUE');
|
|
632
|
+
return ` ${parts.join(' ')}`;
|
|
633
|
+
});
|
|
634
|
+
await write(adapter, `CREATE TABLE ${quote(table)} (\n${lines.join(',\n')}\n)`, input.target);
|
|
635
|
+
|
|
636
|
+
if (!input.withData) continue;
|
|
637
|
+
|
|
638
|
+
const rows = await read(adapter, `SELECT * FROM ${quote(table)}`, input.source);
|
|
639
|
+
const names = rows.columns.map((column) => column.name);
|
|
640
|
+
const columnSql = names.map(quote).join(', ');
|
|
641
|
+
|
|
642
|
+
for (let offset = 0; offset < rows.rows.length; offset += ROW_BATCH) {
|
|
643
|
+
const values = rows.rows
|
|
644
|
+
.slice(offset, offset + ROW_BATCH)
|
|
645
|
+
.map((row) => `(${names.map((name) => literal(row[name])).join(', ')})`)
|
|
646
|
+
.join(', ');
|
|
647
|
+
await write(
|
|
648
|
+
adapter,
|
|
649
|
+
`INSERT INTO ${quote(table)} (${columnSql}) VALUES ${values}`,
|
|
650
|
+
input.target
|
|
651
|
+
);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* A value as SQL text.
|
|
658
|
+
*
|
|
659
|
+
* Literals rather than parameters because the statement is assembled in batches
|
|
660
|
+
* of five hundred rows, and a placeholder list that long is slower than the
|
|
661
|
+
* string it would replace. Every branch escapes; the identifiers around it are
|
|
662
|
+
* quoted by the driver's own quoter, which rejects what it cannot escape.
|
|
663
|
+
*/
|
|
664
|
+
function literal(value: unknown): string {
|
|
665
|
+
if (value === null || value === undefined) return 'NULL';
|
|
666
|
+
if (typeof value === 'number' || typeof value === 'bigint') return String(value);
|
|
667
|
+
if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE';
|
|
668
|
+
if (value instanceof Date) return `'${value.toISOString()}'`;
|
|
669
|
+
if (value instanceof Uint8Array) return `'\\x${Buffer.from(value).toString('hex')}'`;
|
|
670
|
+
if (typeof value === 'object') return `'${JSON.stringify(value).replace(/'/g, "''")}'`;
|
|
671
|
+
return `'${String(value).replace(/'/g, "''")}'`;
|
|
672
|
+
}
|