drizzle-multitenant 1.2.0 → 1.3.1
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/README.md +28 -8
- package/dist/cli/index.js +1809 -5949
- package/dist/{context-Vki959ri.d.ts → context-BBLPNjmk.d.ts} +1 -1
- package/dist/cross-schema/index.js +1 -426
- package/dist/export/index.d.ts +395 -0
- package/dist/export/index.js +9 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +34 -4745
- package/dist/integrations/express.d.ts +3 -3
- package/dist/integrations/express.js +1 -110
- package/dist/integrations/fastify.d.ts +3 -3
- package/dist/integrations/fastify.js +1 -236
- package/dist/integrations/hono.js +0 -3
- package/dist/integrations/nestjs/index.d.ts +1 -1
- package/dist/integrations/nestjs/index.js +3 -11006
- package/dist/lint/index.d.ts +475 -0
- package/dist/lint/index.js +5 -0
- package/dist/metrics/index.d.ts +530 -0
- package/dist/metrics/index.js +3 -0
- package/dist/migrator/index.d.ts +116 -4
- package/dist/migrator/index.js +34 -2990
- package/dist/{migrator-BDgFzSh8.d.ts → migrator-C7FtsZ0H.d.ts} +263 -2
- package/dist/scaffold/index.d.ts +330 -0
- package/dist/scaffold/index.js +277 -0
- package/dist/{types-BhK96FPC.d.ts → types-CGqsPe2Q.d.ts} +49 -1
- package/package.json +18 -1
- package/dist/cli/index.js.map +0 -1
- package/dist/cross-schema/index.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/integrations/express.js.map +0 -1
- package/dist/integrations/fastify.js.map +0 -1
- package/dist/integrations/hono.js.map +0 -1
- package/dist/integrations/nestjs/index.js.map +0 -1
- package/dist/migrator/index.js.map +0 -1
package/dist/migrator/index.js
CHANGED
|
@@ -1,348 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { join, basename } from 'path';
|
|
3
|
-
import { createHash } from 'crypto';
|
|
4
|
-
import { Pool } from 'pg';
|
|
5
|
-
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
6
|
-
|
|
7
|
-
// src/migrator/migrator.ts
|
|
8
|
-
|
|
9
|
-
// src/migrator/table-format.ts
|
|
10
|
-
var DEFAULT_FORMAT = {
|
|
11
|
-
format: "name",
|
|
12
|
-
tableName: "__drizzle_migrations",
|
|
13
|
-
columns: {
|
|
14
|
-
identifier: "name",
|
|
15
|
-
timestamp: "applied_at",
|
|
16
|
-
timestampType: "timestamp"
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
var DRIZZLE_KIT_FORMAT = {
|
|
20
|
-
format: "drizzle-kit",
|
|
21
|
-
tableName: "__drizzle_migrations",
|
|
22
|
-
columns: {
|
|
23
|
-
identifier: "hash",
|
|
24
|
-
timestamp: "created_at",
|
|
25
|
-
timestampType: "bigint"
|
|
26
|
-
}
|
|
27
|
-
};
|
|
28
|
-
async function detectTableFormat(pool, schemaName, tableName) {
|
|
29
|
-
const tableExists = await pool.query(
|
|
30
|
-
`SELECT EXISTS (
|
|
1
|
+
import {readdir,readFile}from'fs/promises';import {join,basename}from'path';import {createHash}from'crypto';import {existsSync}from'fs';import {Pool}from'pg';import {drizzle}from'drizzle-orm/node-postgres';var ne={format:"name",tableName:"__drizzle_migrations",columns:{identifier:"name",timestamp:"applied_at",timestampType:"timestamp"}},ae={format:"drizzle-kit",tableName:"__drizzle_migrations",columns:{identifier:"hash",timestamp:"created_at",timestampType:"bigint"}};async function N(m,e,n){if(!(await m.query(`SELECT EXISTS (
|
|
31
2
|
SELECT 1 FROM information_schema.tables
|
|
32
3
|
WHERE table_schema = $1 AND table_name = $2
|
|
33
|
-
) as exists`,
|
|
34
|
-
[schemaName, tableName]
|
|
35
|
-
);
|
|
36
|
-
if (!tableExists.rows[0]?.exists) {
|
|
37
|
-
return null;
|
|
38
|
-
}
|
|
39
|
-
const columnsResult = await pool.query(
|
|
40
|
-
`SELECT column_name, data_type
|
|
4
|
+
) as exists`,[e,n])).rows[0]?.exists)return null;let r=await m.query(`SELECT column_name, data_type
|
|
41
5
|
FROM information_schema.columns
|
|
42
|
-
WHERE table_schema = $1 AND table_name = $2`,
|
|
43
|
-
|
|
44
|
-
);
|
|
45
|
-
const columnMap = new Map(
|
|
46
|
-
columnsResult.rows.map((r) => [r.column_name, r.data_type])
|
|
47
|
-
);
|
|
48
|
-
if (columnMap.has("name")) {
|
|
49
|
-
return {
|
|
50
|
-
format: "name",
|
|
51
|
-
tableName,
|
|
52
|
-
columns: {
|
|
53
|
-
identifier: "name",
|
|
54
|
-
timestamp: columnMap.has("applied_at") ? "applied_at" : "created_at",
|
|
55
|
-
timestampType: "timestamp"
|
|
56
|
-
}
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
if (columnMap.has("hash")) {
|
|
60
|
-
const createdAtType = columnMap.get("created_at");
|
|
61
|
-
if (createdAtType === "bigint") {
|
|
62
|
-
return {
|
|
63
|
-
format: "drizzle-kit",
|
|
64
|
-
tableName,
|
|
65
|
-
columns: {
|
|
66
|
-
identifier: "hash",
|
|
67
|
-
timestamp: "created_at",
|
|
68
|
-
timestampType: "bigint"
|
|
69
|
-
}
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
return {
|
|
73
|
-
format: "hash",
|
|
74
|
-
tableName,
|
|
75
|
-
columns: {
|
|
76
|
-
identifier: "hash",
|
|
77
|
-
timestamp: "created_at",
|
|
78
|
-
timestampType: "timestamp"
|
|
79
|
-
}
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
return null;
|
|
83
|
-
}
|
|
84
|
-
function getFormatConfig(format, tableName = "__drizzle_migrations") {
|
|
85
|
-
switch (format) {
|
|
86
|
-
case "name":
|
|
87
|
-
return {
|
|
88
|
-
format: "name",
|
|
89
|
-
tableName,
|
|
90
|
-
columns: {
|
|
91
|
-
identifier: "name",
|
|
92
|
-
timestamp: "applied_at",
|
|
93
|
-
timestampType: "timestamp"
|
|
94
|
-
}
|
|
95
|
-
};
|
|
96
|
-
case "hash":
|
|
97
|
-
return {
|
|
98
|
-
format: "hash",
|
|
99
|
-
tableName,
|
|
100
|
-
columns: {
|
|
101
|
-
identifier: "hash",
|
|
102
|
-
timestamp: "created_at",
|
|
103
|
-
timestampType: "timestamp"
|
|
104
|
-
}
|
|
105
|
-
};
|
|
106
|
-
case "drizzle-kit":
|
|
107
|
-
return {
|
|
108
|
-
format: "drizzle-kit",
|
|
109
|
-
tableName,
|
|
110
|
-
columns: {
|
|
111
|
-
identifier: "hash",
|
|
112
|
-
timestamp: "created_at",
|
|
113
|
-
timestampType: "bigint"
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
var DEFAULT_MIGRATIONS_TABLE = "__drizzle_migrations";
|
|
119
|
-
var SchemaManager = class {
|
|
120
|
-
constructor(config, migrationsTable) {
|
|
121
|
-
this.config = config;
|
|
122
|
-
this.migrationsTable = migrationsTable ?? DEFAULT_MIGRATIONS_TABLE;
|
|
123
|
-
}
|
|
124
|
-
migrationsTable;
|
|
125
|
-
/**
|
|
126
|
-
* Get the schema name for a tenant ID using the configured template
|
|
127
|
-
*
|
|
128
|
-
* @param tenantId - The tenant identifier
|
|
129
|
-
* @returns The PostgreSQL schema name
|
|
130
|
-
*
|
|
131
|
-
* @example
|
|
132
|
-
* ```typescript
|
|
133
|
-
* const schemaName = schemaManager.getSchemaName('tenant-123');
|
|
134
|
-
* // Returns: 'tenant_tenant-123' (depends on schemaNameTemplate)
|
|
135
|
-
* ```
|
|
136
|
-
*/
|
|
137
|
-
getSchemaName(tenantId) {
|
|
138
|
-
return this.config.isolation.schemaNameTemplate(tenantId);
|
|
139
|
-
}
|
|
140
|
-
/**
|
|
141
|
-
* Create a PostgreSQL pool for a specific schema
|
|
142
|
-
*
|
|
143
|
-
* The pool is configured with `search_path` set to the schema,
|
|
144
|
-
* allowing queries to run in tenant isolation.
|
|
145
|
-
*
|
|
146
|
-
* @param schemaName - The PostgreSQL schema name
|
|
147
|
-
* @returns A configured Pool instance
|
|
148
|
-
*
|
|
149
|
-
* @example
|
|
150
|
-
* ```typescript
|
|
151
|
-
* const pool = await schemaManager.createPool('tenant_123');
|
|
152
|
-
* try {
|
|
153
|
-
* await pool.query('SELECT * FROM users'); // Queries tenant_123.users
|
|
154
|
-
* } finally {
|
|
155
|
-
* await pool.end();
|
|
156
|
-
* }
|
|
157
|
-
* ```
|
|
158
|
-
*/
|
|
159
|
-
async createPool(schemaName) {
|
|
160
|
-
return new Pool({
|
|
161
|
-
connectionString: this.config.connection.url,
|
|
162
|
-
...this.config.connection.poolConfig,
|
|
163
|
-
options: `-c search_path="${schemaName}",public`
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Create a PostgreSQL pool without schema-specific search_path
|
|
168
|
-
*
|
|
169
|
-
* Used for operations that need to work across schemas or
|
|
170
|
-
* before a schema exists (like creating the schema itself).
|
|
171
|
-
*
|
|
172
|
-
* @returns A Pool instance connected to the database
|
|
173
|
-
*/
|
|
174
|
-
async createRootPool() {
|
|
175
|
-
return new Pool({
|
|
176
|
-
connectionString: this.config.connection.url,
|
|
177
|
-
...this.config.connection.poolConfig
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Create a new tenant schema in the database
|
|
182
|
-
*
|
|
183
|
-
* @param tenantId - The tenant identifier
|
|
184
|
-
* @returns Promise that resolves when schema is created
|
|
185
|
-
*
|
|
186
|
-
* @example
|
|
187
|
-
* ```typescript
|
|
188
|
-
* await schemaManager.createSchema('new-tenant');
|
|
189
|
-
* ```
|
|
190
|
-
*/
|
|
191
|
-
async createSchema(tenantId) {
|
|
192
|
-
const schemaName = this.getSchemaName(tenantId);
|
|
193
|
-
const pool = await this.createRootPool();
|
|
194
|
-
try {
|
|
195
|
-
await pool.query(`CREATE SCHEMA IF NOT EXISTS "${schemaName}"`);
|
|
196
|
-
} finally {
|
|
197
|
-
await pool.end();
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* Drop a tenant schema from the database
|
|
202
|
-
*
|
|
203
|
-
* @param tenantId - The tenant identifier
|
|
204
|
-
* @param options - Drop options (cascade, force)
|
|
205
|
-
* @returns Promise that resolves when schema is dropped
|
|
206
|
-
*
|
|
207
|
-
* @example
|
|
208
|
-
* ```typescript
|
|
209
|
-
* // Drop with CASCADE (removes all objects)
|
|
210
|
-
* await schemaManager.dropSchema('old-tenant', { cascade: true });
|
|
211
|
-
*
|
|
212
|
-
* // Drop with RESTRICT (fails if objects exist)
|
|
213
|
-
* await schemaManager.dropSchema('old-tenant', { cascade: false });
|
|
214
|
-
* ```
|
|
215
|
-
*/
|
|
216
|
-
async dropSchema(tenantId, options = {}) {
|
|
217
|
-
const { cascade = true } = options;
|
|
218
|
-
const schemaName = this.getSchemaName(tenantId);
|
|
219
|
-
const pool = await this.createRootPool();
|
|
220
|
-
try {
|
|
221
|
-
const cascadeSql = cascade ? "CASCADE" : "RESTRICT";
|
|
222
|
-
await pool.query(`DROP SCHEMA IF EXISTS "${schemaName}" ${cascadeSql}`);
|
|
223
|
-
} finally {
|
|
224
|
-
await pool.end();
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
/**
|
|
228
|
-
* Check if a tenant schema exists in the database
|
|
229
|
-
*
|
|
230
|
-
* @param tenantId - The tenant identifier
|
|
231
|
-
* @returns True if schema exists, false otherwise
|
|
232
|
-
*
|
|
233
|
-
* @example
|
|
234
|
-
* ```typescript
|
|
235
|
-
* if (await schemaManager.schemaExists('tenant-123')) {
|
|
236
|
-
* console.log('Tenant schema exists');
|
|
237
|
-
* }
|
|
238
|
-
* ```
|
|
239
|
-
*/
|
|
240
|
-
async schemaExists(tenantId) {
|
|
241
|
-
const schemaName = this.getSchemaName(tenantId);
|
|
242
|
-
const pool = await this.createRootPool();
|
|
243
|
-
try {
|
|
244
|
-
const result = await pool.query(
|
|
245
|
-
`SELECT 1 FROM information_schema.schemata WHERE schema_name = $1`,
|
|
246
|
-
[schemaName]
|
|
247
|
-
);
|
|
248
|
-
return result.rowCount !== null && result.rowCount > 0;
|
|
249
|
-
} finally {
|
|
250
|
-
await pool.end();
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
/**
|
|
254
|
-
* List all schemas matching a pattern
|
|
255
|
-
*
|
|
256
|
-
* @param pattern - SQL LIKE pattern to filter schemas (optional)
|
|
257
|
-
* @returns Array of schema names
|
|
258
|
-
*
|
|
259
|
-
* @example
|
|
260
|
-
* ```typescript
|
|
261
|
-
* // List all tenant schemas
|
|
262
|
-
* const schemas = await schemaManager.listSchemas('tenant_%');
|
|
263
|
-
* ```
|
|
264
|
-
*/
|
|
265
|
-
async listSchemas(pattern) {
|
|
266
|
-
const pool = await this.createRootPool();
|
|
267
|
-
try {
|
|
268
|
-
const query = pattern ? `SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE $1 ORDER BY schema_name` : `SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT IN ('pg_catalog', 'information_schema', 'pg_toast') ORDER BY schema_name`;
|
|
269
|
-
const result = await pool.query(
|
|
270
|
-
query,
|
|
271
|
-
pattern ? [pattern] : []
|
|
272
|
-
);
|
|
273
|
-
return result.rows.map((row) => row.schema_name);
|
|
274
|
-
} finally {
|
|
275
|
-
await pool.end();
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
/**
|
|
279
|
-
* Ensure the migrations table exists with the correct format
|
|
280
|
-
*
|
|
281
|
-
* Creates the migrations tracking table if it doesn't exist,
|
|
282
|
-
* using the appropriate column types based on the format.
|
|
283
|
-
*
|
|
284
|
-
* @param pool - Database pool to use
|
|
285
|
-
* @param schemaName - The schema to create the table in
|
|
286
|
-
* @param format - The detected/configured table format
|
|
287
|
-
*
|
|
288
|
-
* @example
|
|
289
|
-
* ```typescript
|
|
290
|
-
* const pool = await schemaManager.createPool('tenant_123');
|
|
291
|
-
* await schemaManager.ensureMigrationsTable(pool, 'tenant_123', format);
|
|
292
|
-
* ```
|
|
293
|
-
*/
|
|
294
|
-
async ensureMigrationsTable(pool, schemaName, format) {
|
|
295
|
-
const { identifier, timestamp, timestampType } = format.columns;
|
|
296
|
-
const identifierCol = identifier === "name" ? "name VARCHAR(255) NOT NULL UNIQUE" : "hash TEXT NOT NULL";
|
|
297
|
-
const timestampCol = timestampType === "bigint" ? `${timestamp} BIGINT NOT NULL` : `${timestamp} TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP`;
|
|
298
|
-
await pool.query(`
|
|
299
|
-
CREATE TABLE IF NOT EXISTS "${schemaName}"."${format.tableName}" (
|
|
6
|
+
WHERE table_schema = $1 AND table_name = $2`,[e,n]),t=new Map(r.rows.map(i=>[i.column_name,i.data_type]));return t.has("name")?{format:"name",tableName:n,columns:{identifier:"name",timestamp:t.has("applied_at")?"applied_at":"created_at",timestampType:"timestamp"}}:t.has("hash")?t.get("created_at")==="bigint"?{format:"drizzle-kit",tableName:n,columns:{identifier:"hash",timestamp:"created_at",timestampType:"bigint"}}:{format:"hash",tableName:n,columns:{identifier:"hash",timestamp:"created_at",timestampType:"timestamp"}}:null}function w(m,e="__drizzle_migrations"){switch(m){case "name":return {format:"name",tableName:e,columns:{identifier:"name",timestamp:"applied_at",timestampType:"timestamp"}};case "hash":return {format:"hash",tableName:e,columns:{identifier:"hash",timestamp:"created_at",timestampType:"timestamp"}};case "drizzle-kit":return {format:"drizzle-kit",tableName:e,columns:{identifier:"hash",timestamp:"created_at",timestampType:"bigint"}}}}var re="__drizzle_migrations",D=class{constructor(e,n){this.config=e;this.migrationsTable=n??re;}migrationsTable;getSchemaName(e){return this.config.isolation.schemaNameTemplate(e)}async createPool(e){return new Pool({connectionString:this.config.connection.url,...this.config.connection.poolConfig,options:`-c search_path="${e}",public`})}async createRootPool(){return new Pool({connectionString:this.config.connection.url,...this.config.connection.poolConfig})}async createSchema(e){let n=this.getSchemaName(e),a=await this.createRootPool();try{await a.query(`CREATE SCHEMA IF NOT EXISTS "${n}"`);}finally{await a.end();}}async dropSchema(e,n={}){let{cascade:a=true}=n,r=this.getSchemaName(e),t=await this.createRootPool();try{let i=a?"CASCADE":"RESTRICT";await t.query(`DROP SCHEMA IF EXISTS "${r}" ${i}`);}finally{await t.end();}}async schemaExists(e){let n=this.getSchemaName(e),a=await this.createRootPool();try{let r=await a.query("SELECT 1 FROM information_schema.schemata WHERE schema_name = $1",[n]);return r.rowCount!==null&&r.rowCount>0}finally{await a.end();}}async listSchemas(e){let n=await this.createRootPool();try{let a=e?"SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE $1 ORDER BY schema_name":"SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT IN ('pg_catalog', 'information_schema', 'pg_toast') ORDER BY schema_name";return (await n.query(a,e?[e]:[])).rows.map(t=>t.schema_name)}finally{await n.end();}}async ensureMigrationsTable(e,n,a){let{identifier:r,timestamp:t,timestampType:i}=a.columns,s=r==="name"?"name VARCHAR(255) NOT NULL UNIQUE":"hash TEXT NOT NULL",o=i==="bigint"?`${t} BIGINT NOT NULL`:`${t} TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP`;await e.query(`
|
|
7
|
+
CREATE TABLE IF NOT EXISTS "${n}"."${a.tableName}" (
|
|
300
8
|
id SERIAL PRIMARY KEY,
|
|
301
|
-
${
|
|
302
|
-
${
|
|
9
|
+
${s},
|
|
10
|
+
${o}
|
|
303
11
|
)
|
|
304
|
-
`);
|
|
305
|
-
|
|
306
|
-
/**
|
|
307
|
-
* Check if the migrations table exists in a schema
|
|
308
|
-
*
|
|
309
|
-
* @param pool - Database pool to use
|
|
310
|
-
* @param schemaName - The schema to check
|
|
311
|
-
* @returns True if migrations table exists
|
|
312
|
-
*
|
|
313
|
-
* @example
|
|
314
|
-
* ```typescript
|
|
315
|
-
* const pool = await schemaManager.createPool('tenant_123');
|
|
316
|
-
* if (await schemaManager.migrationsTableExists(pool, 'tenant_123')) {
|
|
317
|
-
* console.log('Migrations table exists');
|
|
318
|
-
* }
|
|
319
|
-
* ```
|
|
320
|
-
*/
|
|
321
|
-
async migrationsTableExists(pool, schemaName) {
|
|
322
|
-
const result = await pool.query(
|
|
323
|
-
`SELECT 1 FROM information_schema.tables
|
|
324
|
-
WHERE table_schema = $1 AND table_name = $2`,
|
|
325
|
-
[schemaName, this.migrationsTable]
|
|
326
|
-
);
|
|
327
|
-
return result.rowCount !== null && result.rowCount > 0;
|
|
328
|
-
}
|
|
329
|
-
/**
|
|
330
|
-
* Get the configured migrations table name
|
|
331
|
-
*
|
|
332
|
-
* @returns The migrations table name
|
|
333
|
-
*/
|
|
334
|
-
getMigrationsTableName() {
|
|
335
|
-
return this.migrationsTable;
|
|
336
|
-
}
|
|
337
|
-
};
|
|
338
|
-
function createSchemaManager(config, migrationsTable) {
|
|
339
|
-
return new SchemaManager(config, migrationsTable);
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
// src/migrator/drift/column-analyzer.ts
|
|
343
|
-
async function introspectColumns(pool, schemaName, tableName) {
|
|
344
|
-
const result = await pool.query(
|
|
345
|
-
`SELECT
|
|
12
|
+
`);}async migrationsTableExists(e,n){let a=await e.query(`SELECT 1 FROM information_schema.tables
|
|
13
|
+
WHERE table_schema = $1 AND table_name = $2`,[n,this.migrationsTable]);return a.rowCount!==null&&a.rowCount>0}getMigrationsTableName(){return this.migrationsTable}};function ie(m,e){return new D(m,e)}async function v(m,e,n){return (await m.query(`SELECT
|
|
346
14
|
column_name,
|
|
347
15
|
data_type,
|
|
348
16
|
udt_name,
|
|
@@ -354,94 +22,10 @@ async function introspectColumns(pool, schemaName, tableName) {
|
|
|
354
22
|
ordinal_position
|
|
355
23
|
FROM information_schema.columns
|
|
356
24
|
WHERE table_schema = $1 AND table_name = $2
|
|
357
|
-
ORDER BY ordinal_position`,
|
|
358
|
-
[schemaName, tableName]
|
|
359
|
-
);
|
|
360
|
-
return result.rows.map((row) => ({
|
|
361
|
-
name: row.column_name,
|
|
362
|
-
dataType: row.data_type,
|
|
363
|
-
udtName: row.udt_name,
|
|
364
|
-
isNullable: row.is_nullable === "YES",
|
|
365
|
-
columnDefault: row.column_default,
|
|
366
|
-
characterMaximumLength: row.character_maximum_length,
|
|
367
|
-
numericPrecision: row.numeric_precision,
|
|
368
|
-
numericScale: row.numeric_scale,
|
|
369
|
-
ordinalPosition: row.ordinal_position
|
|
370
|
-
}));
|
|
371
|
-
}
|
|
372
|
-
function normalizeDefault(value) {
|
|
373
|
-
if (value === null) return null;
|
|
374
|
-
return value.replace(/^'(.+)'::.+$/, "$1").replace(/^(.+)::.+$/, "$1").trim();
|
|
375
|
-
}
|
|
376
|
-
function compareColumns(reference, target) {
|
|
377
|
-
const drifts = [];
|
|
378
|
-
const refColMap = new Map(reference.map((c) => [c.name, c]));
|
|
379
|
-
const targetColMap = new Map(target.map((c) => [c.name, c]));
|
|
380
|
-
for (const refCol of reference) {
|
|
381
|
-
const targetCol = targetColMap.get(refCol.name);
|
|
382
|
-
if (!targetCol) {
|
|
383
|
-
drifts.push({
|
|
384
|
-
column: refCol.name,
|
|
385
|
-
type: "missing",
|
|
386
|
-
expected: refCol.dataType,
|
|
387
|
-
description: `Column "${refCol.name}" (${refCol.dataType}) is missing`
|
|
388
|
-
});
|
|
389
|
-
continue;
|
|
390
|
-
}
|
|
391
|
-
if (refCol.udtName !== targetCol.udtName) {
|
|
392
|
-
drifts.push({
|
|
393
|
-
column: refCol.name,
|
|
394
|
-
type: "type_mismatch",
|
|
395
|
-
expected: refCol.udtName,
|
|
396
|
-
actual: targetCol.udtName,
|
|
397
|
-
description: `Column "${refCol.name}" type mismatch: expected "${refCol.udtName}", got "${targetCol.udtName}"`
|
|
398
|
-
});
|
|
399
|
-
}
|
|
400
|
-
if (refCol.isNullable !== targetCol.isNullable) {
|
|
401
|
-
drifts.push({
|
|
402
|
-
column: refCol.name,
|
|
403
|
-
type: "nullable_mismatch",
|
|
404
|
-
expected: refCol.isNullable,
|
|
405
|
-
actual: targetCol.isNullable,
|
|
406
|
-
description: `Column "${refCol.name}" nullable mismatch: expected ${refCol.isNullable ? "NULL" : "NOT NULL"}, got ${targetCol.isNullable ? "NULL" : "NOT NULL"}`
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
const normalizedRefDefault = normalizeDefault(refCol.columnDefault);
|
|
410
|
-
const normalizedTargetDefault = normalizeDefault(targetCol.columnDefault);
|
|
411
|
-
if (normalizedRefDefault !== normalizedTargetDefault) {
|
|
412
|
-
drifts.push({
|
|
413
|
-
column: refCol.name,
|
|
414
|
-
type: "default_mismatch",
|
|
415
|
-
expected: refCol.columnDefault,
|
|
416
|
-
actual: targetCol.columnDefault,
|
|
417
|
-
description: `Column "${refCol.name}" default mismatch: expected "${refCol.columnDefault ?? "none"}", got "${targetCol.columnDefault ?? "none"}"`
|
|
418
|
-
});
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
for (const targetCol of target) {
|
|
422
|
-
if (!refColMap.has(targetCol.name)) {
|
|
423
|
-
drifts.push({
|
|
424
|
-
column: targetCol.name,
|
|
425
|
-
type: "extra",
|
|
426
|
-
actual: targetCol.dataType,
|
|
427
|
-
description: `Extra column "${targetCol.name}" (${targetCol.dataType}) not in reference`
|
|
428
|
-
});
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
return drifts;
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
// src/migrator/drift/index-analyzer.ts
|
|
435
|
-
async function introspectIndexes(pool, schemaName, tableName) {
|
|
436
|
-
const indexResult = await pool.query(
|
|
437
|
-
`SELECT indexname, indexdef
|
|
25
|
+
ORDER BY ordinal_position`,[e,n])).rows.map(r=>({name:r.column_name,dataType:r.data_type,udtName:r.udt_name,isNullable:r.is_nullable==="YES",columnDefault:r.column_default,characterMaximumLength:r.character_maximum_length,numericPrecision:r.numeric_precision,numericScale:r.numeric_scale,ordinalPosition:r.ordinal_position}))}function L(m){return m===null?null:m.replace(/^'(.+)'::.+$/,"$1").replace(/^(.+)::.+$/,"$1").trim()}function q(m,e){let n=[],a=new Map(m.map(t=>[t.name,t])),r=new Map(e.map(t=>[t.name,t]));for(let t of m){let i=r.get(t.name);if(!i){n.push({column:t.name,type:"missing",expected:t.dataType,description:`Column "${t.name}" (${t.dataType}) is missing`});continue}t.udtName!==i.udtName&&n.push({column:t.name,type:"type_mismatch",expected:t.udtName,actual:i.udtName,description:`Column "${t.name}" type mismatch: expected "${t.udtName}", got "${i.udtName}"`}),t.isNullable!==i.isNullable&&n.push({column:t.name,type:"nullable_mismatch",expected:t.isNullable,actual:i.isNullable,description:`Column "${t.name}" nullable mismatch: expected ${t.isNullable?"NULL":"NOT NULL"}, got ${i.isNullable?"NULL":"NOT NULL"}`});let s=L(t.columnDefault),o=L(i.columnDefault);s!==o&&n.push({column:t.name,type:"default_mismatch",expected:t.columnDefault,actual:i.columnDefault,description:`Column "${t.name}" default mismatch: expected "${t.columnDefault??"none"}", got "${i.columnDefault??"none"}"`});}for(let t of e)a.has(t.name)||n.push({column:t.name,type:"extra",actual:t.dataType,description:`Extra column "${t.name}" (${t.dataType}) not in reference`});return n}async function j(m,e,n){let a=await m.query(`SELECT indexname, indexdef
|
|
438
26
|
FROM pg_indexes
|
|
439
27
|
WHERE schemaname = $1 AND tablename = $2
|
|
440
|
-
ORDER BY indexname`,
|
|
441
|
-
[schemaName, tableName]
|
|
442
|
-
);
|
|
443
|
-
const indexDetails = await pool.query(
|
|
444
|
-
`SELECT
|
|
28
|
+
ORDER BY indexname`,[e,n]),r=await m.query(`SELECT
|
|
445
29
|
i.relname as indexname,
|
|
446
30
|
a.attname as column_name,
|
|
447
31
|
ix.indisunique as is_unique,
|
|
@@ -452,77 +36,7 @@ async function introspectIndexes(pool, schemaName, tableName) {
|
|
|
452
36
|
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
|
|
453
37
|
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
454
38
|
WHERE n.nspname = $1 AND t.relname = $2
|
|
455
|
-
ORDER BY i.relname, a.attnum`,
|
|
456
|
-
[schemaName, tableName]
|
|
457
|
-
);
|
|
458
|
-
const indexColumnsMap = /* @__PURE__ */ new Map();
|
|
459
|
-
for (const row of indexDetails.rows) {
|
|
460
|
-
const existing = indexColumnsMap.get(row.indexname);
|
|
461
|
-
if (existing) {
|
|
462
|
-
existing.columns.push(row.column_name);
|
|
463
|
-
} else {
|
|
464
|
-
indexColumnsMap.set(row.indexname, {
|
|
465
|
-
columns: [row.column_name],
|
|
466
|
-
isUnique: row.is_unique,
|
|
467
|
-
isPrimary: row.is_primary
|
|
468
|
-
});
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
return indexResult.rows.map((row) => {
|
|
472
|
-
const details = indexColumnsMap.get(row.indexname);
|
|
473
|
-
return {
|
|
474
|
-
name: row.indexname,
|
|
475
|
-
columns: details?.columns ?? [],
|
|
476
|
-
isUnique: details?.isUnique ?? false,
|
|
477
|
-
isPrimary: details?.isPrimary ?? false,
|
|
478
|
-
definition: row.indexdef
|
|
479
|
-
};
|
|
480
|
-
});
|
|
481
|
-
}
|
|
482
|
-
function compareIndexes(reference, target) {
|
|
483
|
-
const drifts = [];
|
|
484
|
-
const refIndexMap = new Map(reference.map((i) => [i.name, i]));
|
|
485
|
-
const targetIndexMap = new Map(target.map((i) => [i.name, i]));
|
|
486
|
-
for (const refIndex of reference) {
|
|
487
|
-
const targetIndex = targetIndexMap.get(refIndex.name);
|
|
488
|
-
if (!targetIndex) {
|
|
489
|
-
drifts.push({
|
|
490
|
-
index: refIndex.name,
|
|
491
|
-
type: "missing",
|
|
492
|
-
expected: refIndex.definition,
|
|
493
|
-
description: `Index "${refIndex.name}" is missing`
|
|
494
|
-
});
|
|
495
|
-
continue;
|
|
496
|
-
}
|
|
497
|
-
const refCols = refIndex.columns.sort().join(",");
|
|
498
|
-
const targetCols = targetIndex.columns.sort().join(",");
|
|
499
|
-
if (refCols !== targetCols || refIndex.isUnique !== targetIndex.isUnique) {
|
|
500
|
-
drifts.push({
|
|
501
|
-
index: refIndex.name,
|
|
502
|
-
type: "definition_mismatch",
|
|
503
|
-
expected: refIndex.definition,
|
|
504
|
-
actual: targetIndex.definition,
|
|
505
|
-
description: `Index "${refIndex.name}" definition differs`
|
|
506
|
-
});
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
for (const targetIndex of target) {
|
|
510
|
-
if (!refIndexMap.has(targetIndex.name)) {
|
|
511
|
-
drifts.push({
|
|
512
|
-
index: targetIndex.name,
|
|
513
|
-
type: "extra",
|
|
514
|
-
actual: targetIndex.definition,
|
|
515
|
-
description: `Extra index "${targetIndex.name}" not in reference`
|
|
516
|
-
});
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
return drifts;
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
// src/migrator/drift/constraint-analyzer.ts
|
|
523
|
-
async function introspectConstraints(pool, schemaName, tableName) {
|
|
524
|
-
const result = await pool.query(
|
|
525
|
-
`SELECT
|
|
39
|
+
ORDER BY i.relname, a.attnum`,[e,n]),t=new Map;for(let i of r.rows){let s=t.get(i.indexname);s?s.columns.push(i.column_name):t.set(i.indexname,{columns:[i.column_name],isUnique:i.is_unique,isPrimary:i.is_primary});}return a.rows.map(i=>{let s=t.get(i.indexname);return {name:i.indexname,columns:s?.columns??[],isUnique:s?.isUnique??false,isPrimary:s?.isPrimary??false,definition:i.indexdef}})}function I(m,e){let n=[],a=new Map(m.map(t=>[t.name,t])),r=new Map(e.map(t=>[t.name,t]));for(let t of m){let i=r.get(t.name);if(!i){n.push({index:t.name,type:"missing",expected:t.definition,description:`Index "${t.name}" is missing`});continue}let s=t.columns.sort().join(","),o=i.columns.sort().join(",");(s!==o||t.isUnique!==i.isUnique)&&n.push({index:t.name,type:"definition_mismatch",expected:t.definition,actual:i.definition,description:`Index "${t.name}" definition differs`});}for(let t of e)a.has(t.name)||n.push({index:t.name,type:"extra",actual:t.definition,description:`Extra index "${t.name}" not in reference`});return n}async function B(m,e,n){let a=await m.query(`SELECT
|
|
526
40
|
tc.constraint_name,
|
|
527
41
|
tc.constraint_type,
|
|
528
42
|
kcu.column_name,
|
|
@@ -541,1710 +55,20 @@ async function introspectConstraints(pool, schemaName, tableName) {
|
|
|
541
55
|
ON tc.constraint_name = cc.constraint_name
|
|
542
56
|
AND tc.constraint_type = 'CHECK'
|
|
543
57
|
WHERE tc.table_schema = $1 AND tc.table_name = $2
|
|
544
|
-
ORDER BY tc.constraint_name, kcu.ordinal_position`,
|
|
545
|
-
[schemaName, tableName]
|
|
546
|
-
);
|
|
547
|
-
const constraintMap = /* @__PURE__ */ new Map();
|
|
548
|
-
for (const row of result.rows) {
|
|
549
|
-
const existing = constraintMap.get(row.constraint_name);
|
|
550
|
-
if (existing) {
|
|
551
|
-
if (row.column_name && !existing.columns.includes(row.column_name)) {
|
|
552
|
-
existing.columns.push(row.column_name);
|
|
553
|
-
}
|
|
554
|
-
if (row.foreign_column_name && existing.foreignColumns && !existing.foreignColumns.includes(row.foreign_column_name)) {
|
|
555
|
-
existing.foreignColumns.push(row.foreign_column_name);
|
|
556
|
-
}
|
|
557
|
-
} else {
|
|
558
|
-
const constraint = {
|
|
559
|
-
name: row.constraint_name,
|
|
560
|
-
type: row.constraint_type,
|
|
561
|
-
columns: row.column_name ? [row.column_name] : []
|
|
562
|
-
};
|
|
563
|
-
if (row.foreign_table_name) {
|
|
564
|
-
constraint.foreignTable = row.foreign_table_name;
|
|
565
|
-
}
|
|
566
|
-
if (row.foreign_column_name) {
|
|
567
|
-
constraint.foreignColumns = [row.foreign_column_name];
|
|
568
|
-
}
|
|
569
|
-
if (row.check_clause) {
|
|
570
|
-
constraint.checkExpression = row.check_clause;
|
|
571
|
-
}
|
|
572
|
-
constraintMap.set(row.constraint_name, constraint);
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
return Array.from(constraintMap.values());
|
|
576
|
-
}
|
|
577
|
-
function compareConstraints(reference, target) {
|
|
578
|
-
const drifts = [];
|
|
579
|
-
const refConstraintMap = new Map(reference.map((c) => [c.name, c]));
|
|
580
|
-
const targetConstraintMap = new Map(target.map((c) => [c.name, c]));
|
|
581
|
-
for (const refConstraint of reference) {
|
|
582
|
-
const targetConstraint = targetConstraintMap.get(refConstraint.name);
|
|
583
|
-
if (!targetConstraint) {
|
|
584
|
-
drifts.push({
|
|
585
|
-
constraint: refConstraint.name,
|
|
586
|
-
type: "missing",
|
|
587
|
-
expected: `${refConstraint.type} on (${refConstraint.columns.join(", ")})`,
|
|
588
|
-
description: `Constraint "${refConstraint.name}" (${refConstraint.type}) is missing`
|
|
589
|
-
});
|
|
590
|
-
continue;
|
|
591
|
-
}
|
|
592
|
-
const refCols = refConstraint.columns.sort().join(",");
|
|
593
|
-
const targetCols = targetConstraint.columns.sort().join(",");
|
|
594
|
-
if (refConstraint.type !== targetConstraint.type || refCols !== targetCols) {
|
|
595
|
-
drifts.push({
|
|
596
|
-
constraint: refConstraint.name,
|
|
597
|
-
type: "definition_mismatch",
|
|
598
|
-
expected: `${refConstraint.type} on (${refConstraint.columns.join(", ")})`,
|
|
599
|
-
actual: `${targetConstraint.type} on (${targetConstraint.columns.join(", ")})`,
|
|
600
|
-
description: `Constraint "${refConstraint.name}" definition differs`
|
|
601
|
-
});
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
for (const targetConstraint of target) {
|
|
605
|
-
if (!refConstraintMap.has(targetConstraint.name)) {
|
|
606
|
-
drifts.push({
|
|
607
|
-
constraint: targetConstraint.name,
|
|
608
|
-
type: "extra",
|
|
609
|
-
actual: `${targetConstraint.type} on (${targetConstraint.columns.join(", ")})`,
|
|
610
|
-
description: `Extra constraint "${targetConstraint.name}" (${targetConstraint.type}) not in reference`
|
|
611
|
-
});
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
return drifts;
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
// src/migrator/drift/drift-detector.ts
|
|
618
|
-
var DEFAULT_MIGRATIONS_TABLE2 = "__drizzle_migrations";
|
|
619
|
-
var DriftDetector = class {
|
|
620
|
-
constructor(tenantConfig, schemaManager, driftConfig) {
|
|
621
|
-
this.tenantConfig = tenantConfig;
|
|
622
|
-
this.schemaManager = schemaManager;
|
|
623
|
-
this.driftConfig = driftConfig;
|
|
624
|
-
this.migrationsTable = driftConfig.migrationsTable ?? DEFAULT_MIGRATIONS_TABLE2;
|
|
625
|
-
}
|
|
626
|
-
migrationsTable;
|
|
627
|
-
/**
|
|
628
|
-
* Get the schema name for a tenant ID
|
|
629
|
-
*/
|
|
630
|
-
getSchemaName(tenantId) {
|
|
631
|
-
return this.tenantConfig.isolation.schemaNameTemplate(tenantId);
|
|
632
|
-
}
|
|
633
|
-
/**
|
|
634
|
-
* Create a pool for a schema
|
|
635
|
-
*/
|
|
636
|
-
async createPool(schemaName) {
|
|
637
|
-
return this.schemaManager.createPool(schemaName);
|
|
638
|
-
}
|
|
639
|
-
/**
|
|
640
|
-
* Detect schema drift across all tenants.
|
|
641
|
-
*
|
|
642
|
-
* Compares each tenant's schema against a reference tenant (first tenant by default).
|
|
643
|
-
* Returns a comprehensive report of all differences found.
|
|
644
|
-
*
|
|
645
|
-
* @param options - Detection options
|
|
646
|
-
* @returns Schema drift status with details for each tenant
|
|
647
|
-
*
|
|
648
|
-
* @example
|
|
649
|
-
* ```typescript
|
|
650
|
-
* // Basic usage - compare all tenants against the first one
|
|
651
|
-
* const status = await detector.detectDrift();
|
|
652
|
-
*
|
|
653
|
-
* // Use a specific tenant as reference
|
|
654
|
-
* const status = await detector.detectDrift({
|
|
655
|
-
* referenceTenant: 'golden-tenant',
|
|
656
|
-
* });
|
|
657
|
-
*
|
|
658
|
-
* // Check specific tenants only
|
|
659
|
-
* const status = await detector.detectDrift({
|
|
660
|
-
* tenantIds: ['tenant-1', 'tenant-2'],
|
|
661
|
-
* });
|
|
662
|
-
*
|
|
663
|
-
* // Skip index and constraint comparison for faster checks
|
|
664
|
-
* const status = await detector.detectDrift({
|
|
665
|
-
* includeIndexes: false,
|
|
666
|
-
* includeConstraints: false,
|
|
667
|
-
* });
|
|
668
|
-
* ```
|
|
669
|
-
*/
|
|
670
|
-
async detectDrift(options = {}) {
|
|
671
|
-
const startTime = Date.now();
|
|
672
|
-
const {
|
|
673
|
-
concurrency = 10,
|
|
674
|
-
includeIndexes = true,
|
|
675
|
-
includeConstraints = true,
|
|
676
|
-
excludeTables = [this.migrationsTable],
|
|
677
|
-
onProgress
|
|
678
|
-
} = options;
|
|
679
|
-
const tenantIds = options.tenantIds ?? await this.driftConfig.tenantDiscovery();
|
|
680
|
-
if (tenantIds.length === 0) {
|
|
681
|
-
return {
|
|
682
|
-
referenceTenant: "",
|
|
683
|
-
total: 0,
|
|
684
|
-
noDrift: 0,
|
|
685
|
-
withDrift: 0,
|
|
686
|
-
error: 0,
|
|
687
|
-
details: [],
|
|
688
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
689
|
-
durationMs: Date.now() - startTime
|
|
690
|
-
};
|
|
691
|
-
}
|
|
692
|
-
const referenceTenant = options.referenceTenant ?? tenantIds[0];
|
|
693
|
-
onProgress?.(referenceTenant, "starting");
|
|
694
|
-
onProgress?.(referenceTenant, "introspecting");
|
|
695
|
-
const referenceSchema = await this.introspectSchema(referenceTenant, {
|
|
696
|
-
includeIndexes,
|
|
697
|
-
includeConstraints,
|
|
698
|
-
excludeTables
|
|
699
|
-
});
|
|
700
|
-
if (!referenceSchema) {
|
|
701
|
-
return {
|
|
702
|
-
referenceTenant,
|
|
703
|
-
total: tenantIds.length,
|
|
704
|
-
noDrift: 0,
|
|
705
|
-
withDrift: 0,
|
|
706
|
-
error: tenantIds.length,
|
|
707
|
-
details: tenantIds.map((id) => ({
|
|
708
|
-
tenantId: id,
|
|
709
|
-
schemaName: this.getSchemaName(id),
|
|
710
|
-
hasDrift: false,
|
|
711
|
-
tables: [],
|
|
712
|
-
issueCount: 0,
|
|
713
|
-
error: id === referenceTenant ? "Failed to introspect reference tenant" : "Reference tenant introspection failed"
|
|
714
|
-
})),
|
|
715
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
716
|
-
durationMs: Date.now() - startTime
|
|
717
|
-
};
|
|
718
|
-
}
|
|
719
|
-
onProgress?.(referenceTenant, "completed");
|
|
720
|
-
const tenantsToCheck = tenantIds.filter((id) => id !== referenceTenant);
|
|
721
|
-
const results = [];
|
|
722
|
-
results.push({
|
|
723
|
-
tenantId: referenceTenant,
|
|
724
|
-
schemaName: referenceSchema.schemaName,
|
|
725
|
-
hasDrift: false,
|
|
726
|
-
tables: [],
|
|
727
|
-
issueCount: 0
|
|
728
|
-
});
|
|
729
|
-
for (let i = 0; i < tenantsToCheck.length; i += concurrency) {
|
|
730
|
-
const batch = tenantsToCheck.slice(i, i + concurrency);
|
|
731
|
-
const batchResults = await Promise.all(
|
|
732
|
-
batch.map(async (tenantId) => {
|
|
733
|
-
try {
|
|
734
|
-
onProgress?.(tenantId, "starting");
|
|
735
|
-
onProgress?.(tenantId, "introspecting");
|
|
736
|
-
const tenantSchema = await this.introspectSchema(tenantId, {
|
|
737
|
-
includeIndexes,
|
|
738
|
-
includeConstraints,
|
|
739
|
-
excludeTables
|
|
740
|
-
});
|
|
741
|
-
if (!tenantSchema) {
|
|
742
|
-
onProgress?.(tenantId, "failed");
|
|
743
|
-
return {
|
|
744
|
-
tenantId,
|
|
745
|
-
schemaName: this.getSchemaName(tenantId),
|
|
746
|
-
hasDrift: false,
|
|
747
|
-
tables: [],
|
|
748
|
-
issueCount: 0,
|
|
749
|
-
error: "Failed to introspect schema"
|
|
750
|
-
};
|
|
751
|
-
}
|
|
752
|
-
onProgress?.(tenantId, "comparing");
|
|
753
|
-
const drift = this.compareSchemas(referenceSchema, tenantSchema, {
|
|
754
|
-
includeIndexes,
|
|
755
|
-
includeConstraints
|
|
756
|
-
});
|
|
757
|
-
onProgress?.(tenantId, "completed");
|
|
758
|
-
return drift;
|
|
759
|
-
} catch (error) {
|
|
760
|
-
onProgress?.(tenantId, "failed");
|
|
761
|
-
return {
|
|
762
|
-
tenantId,
|
|
763
|
-
schemaName: this.getSchemaName(tenantId),
|
|
764
|
-
hasDrift: false,
|
|
765
|
-
tables: [],
|
|
766
|
-
issueCount: 0,
|
|
767
|
-
error: error.message
|
|
768
|
-
};
|
|
769
|
-
}
|
|
770
|
-
})
|
|
771
|
-
);
|
|
772
|
-
results.push(...batchResults);
|
|
773
|
-
}
|
|
774
|
-
return {
|
|
775
|
-
referenceTenant,
|
|
776
|
-
total: results.length,
|
|
777
|
-
noDrift: results.filter((r) => !r.hasDrift && !r.error).length,
|
|
778
|
-
withDrift: results.filter((r) => r.hasDrift && !r.error).length,
|
|
779
|
-
error: results.filter((r) => !!r.error).length,
|
|
780
|
-
details: results,
|
|
781
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
782
|
-
durationMs: Date.now() - startTime
|
|
783
|
-
};
|
|
784
|
-
}
|
|
785
|
-
/**
|
|
786
|
-
* Compare a specific tenant against a reference tenant.
|
|
787
|
-
*
|
|
788
|
-
* @param tenantId - Tenant to check
|
|
789
|
-
* @param referenceTenantId - Tenant to use as reference
|
|
790
|
-
* @param options - Introspection options
|
|
791
|
-
* @returns Drift details for the tenant
|
|
792
|
-
*
|
|
793
|
-
* @example
|
|
794
|
-
* ```typescript
|
|
795
|
-
* const drift = await detector.compareTenant('tenant-123', 'golden-tenant');
|
|
796
|
-
* if (drift.hasDrift) {
|
|
797
|
-
* console.log(`Found ${drift.issueCount} issues`);
|
|
798
|
-
* }
|
|
799
|
-
* ```
|
|
800
|
-
*/
|
|
801
|
-
async compareTenant(tenantId, referenceTenantId, options = {}) {
|
|
802
|
-
const {
|
|
803
|
-
includeIndexes = true,
|
|
804
|
-
includeConstraints = true,
|
|
805
|
-
excludeTables = [this.migrationsTable]
|
|
806
|
-
} = options;
|
|
807
|
-
const referenceSchema = await this.introspectSchema(referenceTenantId, {
|
|
808
|
-
includeIndexes,
|
|
809
|
-
includeConstraints,
|
|
810
|
-
excludeTables
|
|
811
|
-
});
|
|
812
|
-
if (!referenceSchema) {
|
|
813
|
-
return {
|
|
814
|
-
tenantId,
|
|
815
|
-
schemaName: this.getSchemaName(tenantId),
|
|
816
|
-
hasDrift: false,
|
|
817
|
-
tables: [],
|
|
818
|
-
issueCount: 0,
|
|
819
|
-
error: "Failed to introspect reference tenant"
|
|
820
|
-
};
|
|
821
|
-
}
|
|
822
|
-
const tenantSchema = await this.introspectSchema(tenantId, {
|
|
823
|
-
includeIndexes,
|
|
824
|
-
includeConstraints,
|
|
825
|
-
excludeTables
|
|
826
|
-
});
|
|
827
|
-
if (!tenantSchema) {
|
|
828
|
-
return {
|
|
829
|
-
tenantId,
|
|
830
|
-
schemaName: this.getSchemaName(tenantId),
|
|
831
|
-
hasDrift: false,
|
|
832
|
-
tables: [],
|
|
833
|
-
issueCount: 0,
|
|
834
|
-
error: "Failed to introspect tenant schema"
|
|
835
|
-
};
|
|
836
|
-
}
|
|
837
|
-
return this.compareSchemas(referenceSchema, tenantSchema, {
|
|
838
|
-
includeIndexes,
|
|
839
|
-
includeConstraints
|
|
840
|
-
});
|
|
841
|
-
}
|
|
842
|
-
/**
|
|
843
|
-
* Introspect a tenant's schema structure.
|
|
844
|
-
*
|
|
845
|
-
* Retrieves all tables, columns, indexes, and constraints
|
|
846
|
-
* for a tenant's schema.
|
|
847
|
-
*
|
|
848
|
-
* @param tenantId - Tenant to introspect
|
|
849
|
-
* @param options - Introspection options
|
|
850
|
-
* @returns Schema structure or null if introspection fails
|
|
851
|
-
*
|
|
852
|
-
* @example
|
|
853
|
-
* ```typescript
|
|
854
|
-
* const schema = await detector.introspectSchema('tenant-123');
|
|
855
|
-
* if (schema) {
|
|
856
|
-
* console.log(`Found ${schema.tables.length} tables`);
|
|
857
|
-
* for (const table of schema.tables) {
|
|
858
|
-
* console.log(` ${table.name}: ${table.columns.length} columns`);
|
|
859
|
-
* }
|
|
860
|
-
* }
|
|
861
|
-
* ```
|
|
862
|
-
*/
|
|
863
|
-
async introspectSchema(tenantId, options = {}) {
|
|
864
|
-
const schemaName = this.getSchemaName(tenantId);
|
|
865
|
-
const pool = await this.createPool(schemaName);
|
|
866
|
-
try {
|
|
867
|
-
const tables = await this.introspectTables(pool, schemaName, options);
|
|
868
|
-
return {
|
|
869
|
-
tenantId,
|
|
870
|
-
schemaName,
|
|
871
|
-
tables,
|
|
872
|
-
introspectedAt: /* @__PURE__ */ new Date()
|
|
873
|
-
};
|
|
874
|
-
} catch {
|
|
875
|
-
return null;
|
|
876
|
-
} finally {
|
|
877
|
-
await pool.end();
|
|
878
|
-
}
|
|
879
|
-
}
|
|
880
|
-
/**
|
|
881
|
-
* Compare two schema snapshots.
|
|
882
|
-
*
|
|
883
|
-
* This method compares pre-introspected schema snapshots,
|
|
884
|
-
* useful when you already have the schema data available.
|
|
885
|
-
*
|
|
886
|
-
* @param reference - Reference (expected) schema
|
|
887
|
-
* @param target - Target (actual) schema
|
|
888
|
-
* @param options - Comparison options
|
|
889
|
-
* @returns Drift details
|
|
890
|
-
*
|
|
891
|
-
* @example
|
|
892
|
-
* ```typescript
|
|
893
|
-
* const refSchema = await detector.introspectSchema('golden-tenant');
|
|
894
|
-
* const targetSchema = await detector.introspectSchema('tenant-123');
|
|
895
|
-
*
|
|
896
|
-
* if (refSchema && targetSchema) {
|
|
897
|
-
* const drift = detector.compareSchemas(refSchema, targetSchema);
|
|
898
|
-
* console.log(`Drift detected: ${drift.hasDrift}`);
|
|
899
|
-
* }
|
|
900
|
-
* ```
|
|
901
|
-
*/
|
|
902
|
-
compareSchemas(reference, target, options = {}) {
|
|
903
|
-
const { includeIndexes = true, includeConstraints = true } = options;
|
|
904
|
-
const tableDrifts = [];
|
|
905
|
-
let totalIssues = 0;
|
|
906
|
-
const refTableMap = new Map(reference.tables.map((t) => [t.name, t]));
|
|
907
|
-
const targetTableMap = new Map(target.tables.map((t) => [t.name, t]));
|
|
908
|
-
for (const refTable of reference.tables) {
|
|
909
|
-
const targetTable = targetTableMap.get(refTable.name);
|
|
910
|
-
if (!targetTable) {
|
|
911
|
-
tableDrifts.push({
|
|
912
|
-
table: refTable.name,
|
|
913
|
-
status: "missing",
|
|
914
|
-
columns: refTable.columns.map((c) => ({
|
|
915
|
-
column: c.name,
|
|
916
|
-
type: "missing",
|
|
917
|
-
expected: c.dataType,
|
|
918
|
-
description: `Column "${c.name}" (${c.dataType}) is missing`
|
|
919
|
-
})),
|
|
920
|
-
indexes: [],
|
|
921
|
-
constraints: []
|
|
922
|
-
});
|
|
923
|
-
totalIssues += refTable.columns.length;
|
|
924
|
-
continue;
|
|
925
|
-
}
|
|
926
|
-
const columnDrifts = compareColumns(refTable.columns, targetTable.columns);
|
|
927
|
-
const indexDrifts = includeIndexes ? compareIndexes(refTable.indexes, targetTable.indexes) : [];
|
|
928
|
-
const constraintDrifts = includeConstraints ? compareConstraints(refTable.constraints, targetTable.constraints) : [];
|
|
929
|
-
const issues = columnDrifts.length + indexDrifts.length + constraintDrifts.length;
|
|
930
|
-
totalIssues += issues;
|
|
931
|
-
if (issues > 0) {
|
|
932
|
-
tableDrifts.push({
|
|
933
|
-
table: refTable.name,
|
|
934
|
-
status: "drifted",
|
|
935
|
-
columns: columnDrifts,
|
|
936
|
-
indexes: indexDrifts,
|
|
937
|
-
constraints: constraintDrifts
|
|
938
|
-
});
|
|
939
|
-
}
|
|
940
|
-
}
|
|
941
|
-
for (const targetTable of target.tables) {
|
|
942
|
-
if (!refTableMap.has(targetTable.name)) {
|
|
943
|
-
tableDrifts.push({
|
|
944
|
-
table: targetTable.name,
|
|
945
|
-
status: "extra",
|
|
946
|
-
columns: targetTable.columns.map((c) => ({
|
|
947
|
-
column: c.name,
|
|
948
|
-
type: "extra",
|
|
949
|
-
actual: c.dataType,
|
|
950
|
-
description: `Extra column "${c.name}" (${c.dataType}) not in reference`
|
|
951
|
-
})),
|
|
952
|
-
indexes: [],
|
|
953
|
-
constraints: []
|
|
954
|
-
});
|
|
955
|
-
totalIssues += targetTable.columns.length;
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
return {
|
|
959
|
-
tenantId: target.tenantId,
|
|
960
|
-
schemaName: target.schemaName,
|
|
961
|
-
hasDrift: totalIssues > 0,
|
|
962
|
-
tables: tableDrifts,
|
|
963
|
-
issueCount: totalIssues
|
|
964
|
-
};
|
|
965
|
-
}
|
|
966
|
-
/**
|
|
967
|
-
* Introspect all tables in a schema
|
|
968
|
-
*/
|
|
969
|
-
async introspectTables(pool, schemaName, options) {
|
|
970
|
-
const { includeIndexes = true, includeConstraints = true, excludeTables = [] } = options;
|
|
971
|
-
const tablesResult = await pool.query(
|
|
972
|
-
`SELECT table_name
|
|
58
|
+
ORDER BY tc.constraint_name, kcu.ordinal_position`,[e,n]),r=new Map;for(let t of a.rows){let i=r.get(t.constraint_name);if(i)t.column_name&&!i.columns.includes(t.column_name)&&i.columns.push(t.column_name),t.foreign_column_name&&i.foreignColumns&&!i.foreignColumns.includes(t.foreign_column_name)&&i.foreignColumns.push(t.foreign_column_name);else {let s={name:t.constraint_name,type:t.constraint_type,columns:t.column_name?[t.column_name]:[]};t.foreign_table_name&&(s.foreignTable=t.foreign_table_name),t.foreign_column_name&&(s.foreignColumns=[t.foreign_column_name]),t.check_clause&&(s.checkExpression=t.check_clause),r.set(t.constraint_name,s);}}return Array.from(r.values())}function z(m,e){let n=[],a=new Map(m.map(t=>[t.name,t])),r=new Map(e.map(t=>[t.name,t]));for(let t of m){let i=r.get(t.name);if(!i){n.push({constraint:t.name,type:"missing",expected:`${t.type} on (${t.columns.join(", ")})`,description:`Constraint "${t.name}" (${t.type}) is missing`});continue}let s=t.columns.sort().join(","),o=i.columns.sort().join(",");(t.type!==i.type||s!==o)&&n.push({constraint:t.name,type:"definition_mismatch",expected:`${t.type} on (${t.columns.join(", ")})`,actual:`${i.type} on (${i.columns.join(", ")})`,description:`Constraint "${t.name}" definition differs`});}for(let t of e)a.has(t.name)||n.push({constraint:t.name,type:"extra",actual:`${t.type} on (${t.columns.join(", ")})`,description:`Extra constraint "${t.name}" (${t.type}) not in reference`});return n}var se="__drizzle_migrations",O=class{constructor(e,n,a){this.tenantConfig=e;this.schemaManager=n;this.driftConfig=a;this.migrationsTable=a.migrationsTable??se;}migrationsTable;getSchemaName(e){return this.tenantConfig.isolation.schemaNameTemplate(e)}async createPool(e){return this.schemaManager.createPool(e)}async detectDrift(e={}){let n=Date.now(),{concurrency:a=10,includeIndexes:r=true,includeConstraints:t=true,excludeTables:i=[this.migrationsTable],onProgress:s}=e,o=e.tenantIds??await this.driftConfig.tenantDiscovery();if(o.length===0)return {referenceTenant:"",total:0,noDrift:0,withDrift:0,error:0,details:[],timestamp:new Date().toISOString(),durationMs:Date.now()-n};let l=e.referenceTenant??o[0];s?.(l,"starting"),s?.(l,"introspecting");let c=await this.introspectSchema(l,{includeIndexes:r,includeConstraints:t,excludeTables:i});if(!c)return {referenceTenant:l,total:o.length,noDrift:0,withDrift:0,error:o.length,details:o.map(p=>({tenantId:p,schemaName:this.getSchemaName(p),hasDrift:false,tables:[],issueCount:0,error:p===l?"Failed to introspect reference tenant":"Reference tenant introspection failed"})),timestamp:new Date().toISOString(),durationMs:Date.now()-n};s?.(l,"completed");let u=o.filter(p=>p!==l),g=[];g.push({tenantId:l,schemaName:c.schemaName,hasDrift:false,tables:[],issueCount:0});for(let p=0;p<u.length;p+=a){let h=u.slice(p,p+a),y=await Promise.all(h.map(async d=>{try{s?.(d,"starting"),s?.(d,"introspecting");let f=await this.introspectSchema(d,{includeIndexes:r,includeConstraints:t,excludeTables:i});if(!f)return s?.(d,"failed"),{tenantId:d,schemaName:this.getSchemaName(d),hasDrift:!1,tables:[],issueCount:0,error:"Failed to introspect schema"};s?.(d,"comparing");let P=this.compareSchemas(c,f,{includeIndexes:r,includeConstraints:t});return s?.(d,"completed"),P}catch(f){return s?.(d,"failed"),{tenantId:d,schemaName:this.getSchemaName(d),hasDrift:false,tables:[],issueCount:0,error:f.message}}}));g.push(...y);}return {referenceTenant:l,total:g.length,noDrift:g.filter(p=>!p.hasDrift&&!p.error).length,withDrift:g.filter(p=>p.hasDrift&&!p.error).length,error:g.filter(p=>!!p.error).length,details:g,timestamp:new Date().toISOString(),durationMs:Date.now()-n}}async compareTenant(e,n,a={}){let{includeIndexes:r=true,includeConstraints:t=true,excludeTables:i=[this.migrationsTable]}=a,s=await this.introspectSchema(n,{includeIndexes:r,includeConstraints:t,excludeTables:i});if(!s)return {tenantId:e,schemaName:this.getSchemaName(e),hasDrift:false,tables:[],issueCount:0,error:"Failed to introspect reference tenant"};let o=await this.introspectSchema(e,{includeIndexes:r,includeConstraints:t,excludeTables:i});return o?this.compareSchemas(s,o,{includeIndexes:r,includeConstraints:t}):{tenantId:e,schemaName:this.getSchemaName(e),hasDrift:false,tables:[],issueCount:0,error:"Failed to introspect tenant schema"}}async introspectSchema(e,n={}){let a=this.getSchemaName(e),r=await this.createPool(a);try{let t=await this.introspectTables(r,a,n);return {tenantId:e,schemaName:a,tables:t,introspectedAt:new Date}}catch{return null}finally{await r.end();}}compareSchemas(e,n,a={}){let{includeIndexes:r=true,includeConstraints:t=true}=a,i=[],s=0,o=new Map(e.tables.map(c=>[c.name,c])),l=new Map(n.tables.map(c=>[c.name,c]));for(let c of e.tables){let u=l.get(c.name);if(!u){i.push({table:c.name,status:"missing",columns:c.columns.map(d=>({column:d.name,type:"missing",expected:d.dataType,description:`Column "${d.name}" (${d.dataType}) is missing`})),indexes:[],constraints:[]}),s+=c.columns.length;continue}let g=q(c.columns,u.columns),p=r?I(c.indexes,u.indexes):[],h=t?z(c.constraints,u.constraints):[],y=g.length+p.length+h.length;s+=y,y>0&&i.push({table:c.name,status:"drifted",columns:g,indexes:p,constraints:h});}for(let c of n.tables)o.has(c.name)||(i.push({table:c.name,status:"extra",columns:c.columns.map(u=>({column:u.name,type:"extra",actual:u.dataType,description:`Extra column "${u.name}" (${u.dataType}) not in reference`})),indexes:[],constraints:[]}),s+=c.columns.length);return {tenantId:n.tenantId,schemaName:n.schemaName,hasDrift:s>0,tables:i,issueCount:s}}async introspectTables(e,n,a){let{includeIndexes:r=true,includeConstraints:t=true,excludeTables:i=[]}=a,s=await e.query(`SELECT table_name
|
|
973
59
|
FROM information_schema.tables
|
|
974
60
|
WHERE table_schema = $1
|
|
975
61
|
AND table_type = 'BASE TABLE'
|
|
976
|
-
ORDER BY table_name`,
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
if (excludeTables.includes(row.table_name)) {
|
|
982
|
-
continue;
|
|
983
|
-
}
|
|
984
|
-
const columns = await introspectColumns(pool, schemaName, row.table_name);
|
|
985
|
-
const indexes = includeIndexes ? await introspectIndexes(pool, schemaName, row.table_name) : [];
|
|
986
|
-
const constraints = includeConstraints ? await introspectConstraints(pool, schemaName, row.table_name) : [];
|
|
987
|
-
tables.push({
|
|
988
|
-
name: row.table_name,
|
|
989
|
-
columns,
|
|
990
|
-
indexes,
|
|
991
|
-
constraints
|
|
992
|
-
});
|
|
993
|
-
}
|
|
994
|
-
return tables;
|
|
995
|
-
}
|
|
996
|
-
};
|
|
997
|
-
var Seeder = class {
|
|
998
|
-
constructor(config, deps) {
|
|
999
|
-
this.config = config;
|
|
1000
|
-
this.deps = deps;
|
|
1001
|
-
}
|
|
1002
|
-
/**
|
|
1003
|
-
* Seed a single tenant with initial data
|
|
1004
|
-
*
|
|
1005
|
-
* Creates a database connection for the tenant, executes the seed function,
|
|
1006
|
-
* and properly cleans up the connection afterward.
|
|
1007
|
-
*
|
|
1008
|
-
* @param tenantId - The tenant identifier
|
|
1009
|
-
* @param seedFn - Function that seeds the database
|
|
1010
|
-
* @returns Result of the seeding operation
|
|
1011
|
-
*
|
|
1012
|
-
* @example
|
|
1013
|
-
* ```typescript
|
|
1014
|
-
* const result = await seeder.seedTenant('tenant-123', async (db, tenantId) => {
|
|
1015
|
-
* await db.insert(users).values([
|
|
1016
|
-
* { name: 'Admin', email: `admin@${tenantId}.com` },
|
|
1017
|
-
* ]);
|
|
1018
|
-
* });
|
|
1019
|
-
*
|
|
1020
|
-
* if (result.success) {
|
|
1021
|
-
* console.log(`Seeded ${result.tenantId} in ${result.durationMs}ms`);
|
|
1022
|
-
* }
|
|
1023
|
-
* ```
|
|
1024
|
-
*/
|
|
1025
|
-
async seedTenant(tenantId, seedFn) {
|
|
1026
|
-
const startTime = Date.now();
|
|
1027
|
-
const schemaName = this.deps.schemaNameTemplate(tenantId);
|
|
1028
|
-
const pool = await this.deps.createPool(schemaName);
|
|
1029
|
-
try {
|
|
1030
|
-
const db = drizzle(pool, {
|
|
1031
|
-
schema: this.deps.tenantSchema
|
|
1032
|
-
});
|
|
1033
|
-
await seedFn(db, tenantId);
|
|
1034
|
-
return {
|
|
1035
|
-
tenantId,
|
|
1036
|
-
schemaName,
|
|
1037
|
-
success: true,
|
|
1038
|
-
durationMs: Date.now() - startTime
|
|
1039
|
-
};
|
|
1040
|
-
} catch (error) {
|
|
1041
|
-
return {
|
|
1042
|
-
tenantId,
|
|
1043
|
-
schemaName,
|
|
1044
|
-
success: false,
|
|
1045
|
-
error: error.message,
|
|
1046
|
-
durationMs: Date.now() - startTime
|
|
1047
|
-
};
|
|
1048
|
-
} finally {
|
|
1049
|
-
await pool.end();
|
|
1050
|
-
}
|
|
1051
|
-
}
|
|
1052
|
-
/**
|
|
1053
|
-
* Seed all tenants with initial data in parallel
|
|
1054
|
-
*
|
|
1055
|
-
* Discovers all tenants and seeds them in batches with configurable concurrency.
|
|
1056
|
-
* Supports progress callbacks and abort-on-error behavior.
|
|
1057
|
-
*
|
|
1058
|
-
* @param seedFn - Function that seeds each database
|
|
1059
|
-
* @param options - Seeding options
|
|
1060
|
-
* @returns Aggregate results of all seeding operations
|
|
1061
|
-
*
|
|
1062
|
-
* @example
|
|
1063
|
-
* ```typescript
|
|
1064
|
-
* const results = await seeder.seedAll(
|
|
1065
|
-
* async (db, tenantId) => {
|
|
1066
|
-
* await db.insert(settings).values({ key: 'initialized', value: 'true' });
|
|
1067
|
-
* },
|
|
1068
|
-
* {
|
|
1069
|
-
* concurrency: 5,
|
|
1070
|
-
* onProgress: (id, status) => console.log(`${id}: ${status}`),
|
|
1071
|
-
* }
|
|
1072
|
-
* );
|
|
1073
|
-
*
|
|
1074
|
-
* console.log(`Succeeded: ${results.succeeded}/${results.total}`);
|
|
1075
|
-
* ```
|
|
1076
|
-
*/
|
|
1077
|
-
async seedAll(seedFn, options = {}) {
|
|
1078
|
-
const { concurrency = 10, onProgress, onError } = options;
|
|
1079
|
-
const tenantIds = await this.config.tenantDiscovery();
|
|
1080
|
-
const results = [];
|
|
1081
|
-
let aborted = false;
|
|
1082
|
-
for (let i = 0; i < tenantIds.length && !aborted; i += concurrency) {
|
|
1083
|
-
const batch = tenantIds.slice(i, i + concurrency);
|
|
1084
|
-
const batchResults = await Promise.all(
|
|
1085
|
-
batch.map(async (tenantId) => {
|
|
1086
|
-
if (aborted) {
|
|
1087
|
-
return this.createSkippedResult(tenantId);
|
|
1088
|
-
}
|
|
1089
|
-
try {
|
|
1090
|
-
onProgress?.(tenantId, "starting");
|
|
1091
|
-
onProgress?.(tenantId, "seeding");
|
|
1092
|
-
const result = await this.seedTenant(tenantId, seedFn);
|
|
1093
|
-
onProgress?.(tenantId, result.success ? "completed" : "failed");
|
|
1094
|
-
return result;
|
|
1095
|
-
} catch (error) {
|
|
1096
|
-
onProgress?.(tenantId, "failed");
|
|
1097
|
-
const action = onError?.(tenantId, error);
|
|
1098
|
-
if (action === "abort") {
|
|
1099
|
-
aborted = true;
|
|
1100
|
-
}
|
|
1101
|
-
return this.createErrorResult(tenantId, error);
|
|
1102
|
-
}
|
|
1103
|
-
})
|
|
1104
|
-
);
|
|
1105
|
-
results.push(...batchResults);
|
|
1106
|
-
}
|
|
1107
|
-
if (aborted) {
|
|
1108
|
-
const remaining = tenantIds.slice(results.length);
|
|
1109
|
-
for (const tenantId of remaining) {
|
|
1110
|
-
results.push(this.createSkippedResult(tenantId));
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
return this.aggregateResults(results);
|
|
1114
|
-
}
|
|
1115
|
-
/**
|
|
1116
|
-
* Seed specific tenants with initial data
|
|
1117
|
-
*
|
|
1118
|
-
* Seeds only the specified tenants in batches with configurable concurrency.
|
|
1119
|
-
*
|
|
1120
|
-
* @param tenantIds - List of tenant IDs to seed
|
|
1121
|
-
* @param seedFn - Function that seeds each database
|
|
1122
|
-
* @param options - Seeding options
|
|
1123
|
-
* @returns Aggregate results of seeding operations
|
|
1124
|
-
*
|
|
1125
|
-
* @example
|
|
1126
|
-
* ```typescript
|
|
1127
|
-
* const results = await seeder.seedTenants(
|
|
1128
|
-
* ['tenant-1', 'tenant-2', 'tenant-3'],
|
|
1129
|
-
* async (db) => {
|
|
1130
|
-
* await db.insert(config).values({ setup: true });
|
|
1131
|
-
* },
|
|
1132
|
-
* { concurrency: 2 }
|
|
1133
|
-
* );
|
|
1134
|
-
* ```
|
|
1135
|
-
*/
|
|
1136
|
-
async seedTenants(tenantIds, seedFn, options = {}) {
|
|
1137
|
-
const { concurrency = 10, onProgress, onError } = options;
|
|
1138
|
-
const results = [];
|
|
1139
|
-
for (let i = 0; i < tenantIds.length; i += concurrency) {
|
|
1140
|
-
const batch = tenantIds.slice(i, i + concurrency);
|
|
1141
|
-
const batchResults = await Promise.all(
|
|
1142
|
-
batch.map(async (tenantId) => {
|
|
1143
|
-
try {
|
|
1144
|
-
onProgress?.(tenantId, "starting");
|
|
1145
|
-
onProgress?.(tenantId, "seeding");
|
|
1146
|
-
const result = await this.seedTenant(tenantId, seedFn);
|
|
1147
|
-
onProgress?.(tenantId, result.success ? "completed" : "failed");
|
|
1148
|
-
return result;
|
|
1149
|
-
} catch (error) {
|
|
1150
|
-
onProgress?.(tenantId, "failed");
|
|
1151
|
-
onError?.(tenantId, error);
|
|
1152
|
-
return this.createErrorResult(tenantId, error);
|
|
1153
|
-
}
|
|
1154
|
-
})
|
|
1155
|
-
);
|
|
1156
|
-
results.push(...batchResults);
|
|
1157
|
-
}
|
|
1158
|
-
return this.aggregateResults(results);
|
|
1159
|
-
}
|
|
1160
|
-
/**
|
|
1161
|
-
* Create a skipped result for aborted seeding
|
|
1162
|
-
*/
|
|
1163
|
-
createSkippedResult(tenantId) {
|
|
1164
|
-
return {
|
|
1165
|
-
tenantId,
|
|
1166
|
-
schemaName: this.deps.schemaNameTemplate(tenantId),
|
|
1167
|
-
success: false,
|
|
1168
|
-
error: "Skipped due to abort",
|
|
1169
|
-
durationMs: 0
|
|
1170
|
-
};
|
|
1171
|
-
}
|
|
1172
|
-
/**
|
|
1173
|
-
* Create an error result for failed seeding
|
|
1174
|
-
*/
|
|
1175
|
-
createErrorResult(tenantId, error) {
|
|
1176
|
-
return {
|
|
1177
|
-
tenantId,
|
|
1178
|
-
schemaName: this.deps.schemaNameTemplate(tenantId),
|
|
1179
|
-
success: false,
|
|
1180
|
-
error: error.message,
|
|
1181
|
-
durationMs: 0
|
|
1182
|
-
};
|
|
1183
|
-
}
|
|
1184
|
-
/**
|
|
1185
|
-
* Aggregate individual results into a summary
|
|
1186
|
-
*/
|
|
1187
|
-
aggregateResults(results) {
|
|
1188
|
-
return {
|
|
1189
|
-
total: results.length,
|
|
1190
|
-
succeeded: results.filter((r) => r.success).length,
|
|
1191
|
-
failed: results.filter(
|
|
1192
|
-
(r) => !r.success && r.error !== "Skipped due to abort"
|
|
1193
|
-
).length,
|
|
1194
|
-
skipped: results.filter((r) => r.error === "Skipped due to abort").length,
|
|
1195
|
-
details: results
|
|
1196
|
-
};
|
|
1197
|
-
}
|
|
1198
|
-
};
|
|
1199
|
-
function createSeeder(config, dependencies) {
|
|
1200
|
-
return new Seeder(config, dependencies);
|
|
1201
|
-
}
|
|
1202
|
-
|
|
1203
|
-
// src/migrator/sync/sync-manager.ts
|
|
1204
|
-
var SyncManager = class {
|
|
1205
|
-
constructor(config, deps) {
|
|
1206
|
-
this.config = config;
|
|
1207
|
-
this.deps = deps;
|
|
1208
|
-
}
|
|
1209
|
-
/**
|
|
1210
|
-
* Get sync status for all tenants
|
|
1211
|
-
*
|
|
1212
|
-
* Detects divergences between migrations on disk and tracking in database.
|
|
1213
|
-
* A tenant is "in sync" when all disk migrations are tracked and no orphan records exist.
|
|
1214
|
-
*
|
|
1215
|
-
* @returns Aggregate sync status for all tenants
|
|
1216
|
-
*
|
|
1217
|
-
* @example
|
|
1218
|
-
* ```typescript
|
|
1219
|
-
* const status = await syncManager.getSyncStatus();
|
|
1220
|
-
* console.log(`Total: ${status.total}, In sync: ${status.inSync}, Out of sync: ${status.outOfSync}`);
|
|
1221
|
-
*
|
|
1222
|
-
* for (const tenant of status.details.filter(d => !d.inSync)) {
|
|
1223
|
-
* console.log(`${tenant.tenantId}: missing=${tenant.missing.length}, orphans=${tenant.orphans.length}`);
|
|
1224
|
-
* }
|
|
1225
|
-
* ```
|
|
1226
|
-
*/
|
|
1227
|
-
async getSyncStatus() {
|
|
1228
|
-
const tenantIds = await this.config.tenantDiscovery();
|
|
1229
|
-
const migrations = await this.deps.loadMigrations();
|
|
1230
|
-
const statuses = [];
|
|
1231
|
-
for (const tenantId of tenantIds) {
|
|
1232
|
-
statuses.push(await this.getTenantSyncStatus(tenantId, migrations));
|
|
1233
|
-
}
|
|
1234
|
-
return {
|
|
1235
|
-
total: statuses.length,
|
|
1236
|
-
inSync: statuses.filter((s) => s.inSync && !s.error).length,
|
|
1237
|
-
outOfSync: statuses.filter((s) => !s.inSync && !s.error).length,
|
|
1238
|
-
error: statuses.filter((s) => !!s.error).length,
|
|
1239
|
-
details: statuses
|
|
1240
|
-
};
|
|
1241
|
-
}
|
|
1242
|
-
/**
|
|
1243
|
-
* Get sync status for a specific tenant
|
|
1244
|
-
*
|
|
1245
|
-
* Compares migrations on disk with records in the database.
|
|
1246
|
-
* Identifies missing migrations (on disk but not tracked) and
|
|
1247
|
-
* orphan records (tracked but not on disk).
|
|
1248
|
-
*
|
|
1249
|
-
* @param tenantId - The tenant identifier
|
|
1250
|
-
* @param migrations - Optional pre-loaded migrations (avoids reloading from disk)
|
|
1251
|
-
* @returns Sync status for the tenant
|
|
1252
|
-
*
|
|
1253
|
-
* @example
|
|
1254
|
-
* ```typescript
|
|
1255
|
-
* const status = await syncManager.getTenantSyncStatus('tenant-123');
|
|
1256
|
-
* if (status.missing.length > 0) {
|
|
1257
|
-
* console.log(`Missing: ${status.missing.join(', ')}`);
|
|
1258
|
-
* }
|
|
1259
|
-
* if (status.orphans.length > 0) {
|
|
1260
|
-
* console.log(`Orphans: ${status.orphans.join(', ')}`);
|
|
1261
|
-
* }
|
|
1262
|
-
* ```
|
|
1263
|
-
*/
|
|
1264
|
-
async getTenantSyncStatus(tenantId, migrations) {
|
|
1265
|
-
const schemaName = this.deps.schemaNameTemplate(tenantId);
|
|
1266
|
-
const pool = await this.deps.createPool(schemaName);
|
|
1267
|
-
try {
|
|
1268
|
-
const allMigrations = migrations ?? await this.deps.loadMigrations();
|
|
1269
|
-
const migrationNames = new Set(allMigrations.map((m) => m.name));
|
|
1270
|
-
const migrationHashes = new Set(allMigrations.map((m) => m.hash));
|
|
1271
|
-
const tableExists = await this.deps.migrationsTableExists(pool, schemaName);
|
|
1272
|
-
if (!tableExists) {
|
|
1273
|
-
return {
|
|
1274
|
-
tenantId,
|
|
1275
|
-
schemaName,
|
|
1276
|
-
missing: allMigrations.map((m) => m.name),
|
|
1277
|
-
orphans: [],
|
|
1278
|
-
inSync: allMigrations.length === 0,
|
|
1279
|
-
format: null
|
|
1280
|
-
};
|
|
1281
|
-
}
|
|
1282
|
-
const format = await this.deps.getOrDetectFormat(pool, schemaName);
|
|
1283
|
-
const applied = await this.getAppliedMigrations(pool, schemaName, format);
|
|
1284
|
-
const appliedIdentifiers = new Set(applied.map((m) => m.identifier));
|
|
1285
|
-
const missing = allMigrations.filter((m) => !this.isMigrationApplied(m, appliedIdentifiers, format)).map((m) => m.name);
|
|
1286
|
-
const orphans = applied.filter((m) => {
|
|
1287
|
-
if (format.columns.identifier === "name") {
|
|
1288
|
-
return !migrationNames.has(m.identifier);
|
|
1289
|
-
}
|
|
1290
|
-
return !migrationHashes.has(m.identifier) && !migrationNames.has(m.identifier);
|
|
1291
|
-
}).map((m) => m.identifier);
|
|
1292
|
-
return {
|
|
1293
|
-
tenantId,
|
|
1294
|
-
schemaName,
|
|
1295
|
-
missing,
|
|
1296
|
-
orphans,
|
|
1297
|
-
inSync: missing.length === 0 && orphans.length === 0,
|
|
1298
|
-
format: format.format
|
|
1299
|
-
};
|
|
1300
|
-
} catch (error) {
|
|
1301
|
-
return {
|
|
1302
|
-
tenantId,
|
|
1303
|
-
schemaName,
|
|
1304
|
-
missing: [],
|
|
1305
|
-
orphans: [],
|
|
1306
|
-
inSync: false,
|
|
1307
|
-
format: null,
|
|
1308
|
-
error: error.message
|
|
1309
|
-
};
|
|
1310
|
-
} finally {
|
|
1311
|
-
await pool.end();
|
|
1312
|
-
}
|
|
1313
|
-
}
|
|
1314
|
-
/**
|
|
1315
|
-
* Mark missing migrations as applied for a tenant
|
|
1316
|
-
*
|
|
1317
|
-
* Records migrations that exist on disk but are not tracked in the database.
|
|
1318
|
-
* Useful for syncing tracking state with already-applied migrations.
|
|
1319
|
-
*
|
|
1320
|
-
* @param tenantId - The tenant identifier
|
|
1321
|
-
* @returns Result of the mark operation
|
|
1322
|
-
*
|
|
1323
|
-
* @example
|
|
1324
|
-
* ```typescript
|
|
1325
|
-
* const result = await syncManager.markMissing('tenant-123');
|
|
1326
|
-
* if (result.success) {
|
|
1327
|
-
* console.log(`Marked ${result.markedMigrations.length} migrations as applied`);
|
|
1328
|
-
* }
|
|
1329
|
-
* ```
|
|
1330
|
-
*/
|
|
1331
|
-
async markMissing(tenantId) {
|
|
1332
|
-
const startTime = Date.now();
|
|
1333
|
-
const schemaName = this.deps.schemaNameTemplate(tenantId);
|
|
1334
|
-
const markedMigrations = [];
|
|
1335
|
-
const pool = await this.deps.createPool(schemaName);
|
|
1336
|
-
try {
|
|
1337
|
-
const syncStatus = await this.getTenantSyncStatus(tenantId);
|
|
1338
|
-
if (syncStatus.error) {
|
|
1339
|
-
return {
|
|
1340
|
-
tenantId,
|
|
1341
|
-
schemaName,
|
|
1342
|
-
success: false,
|
|
1343
|
-
markedMigrations: [],
|
|
1344
|
-
removedOrphans: [],
|
|
1345
|
-
error: syncStatus.error,
|
|
1346
|
-
durationMs: Date.now() - startTime
|
|
1347
|
-
};
|
|
1348
|
-
}
|
|
1349
|
-
if (syncStatus.missing.length === 0) {
|
|
1350
|
-
return {
|
|
1351
|
-
tenantId,
|
|
1352
|
-
schemaName,
|
|
1353
|
-
success: true,
|
|
1354
|
-
markedMigrations: [],
|
|
1355
|
-
removedOrphans: [],
|
|
1356
|
-
durationMs: Date.now() - startTime
|
|
1357
|
-
};
|
|
1358
|
-
}
|
|
1359
|
-
const format = await this.deps.getOrDetectFormat(pool, schemaName);
|
|
1360
|
-
await this.deps.ensureMigrationsTable(pool, schemaName, format);
|
|
1361
|
-
const allMigrations = await this.deps.loadMigrations();
|
|
1362
|
-
const missingSet = new Set(syncStatus.missing);
|
|
1363
|
-
for (const migration of allMigrations) {
|
|
1364
|
-
if (missingSet.has(migration.name)) {
|
|
1365
|
-
await this.recordMigration(pool, schemaName, migration, format);
|
|
1366
|
-
markedMigrations.push(migration.name);
|
|
1367
|
-
}
|
|
1368
|
-
}
|
|
1369
|
-
return {
|
|
1370
|
-
tenantId,
|
|
1371
|
-
schemaName,
|
|
1372
|
-
success: true,
|
|
1373
|
-
markedMigrations,
|
|
1374
|
-
removedOrphans: [],
|
|
1375
|
-
durationMs: Date.now() - startTime
|
|
1376
|
-
};
|
|
1377
|
-
} catch (error) {
|
|
1378
|
-
return {
|
|
1379
|
-
tenantId,
|
|
1380
|
-
schemaName,
|
|
1381
|
-
success: false,
|
|
1382
|
-
markedMigrations,
|
|
1383
|
-
removedOrphans: [],
|
|
1384
|
-
error: error.message,
|
|
1385
|
-
durationMs: Date.now() - startTime
|
|
1386
|
-
};
|
|
1387
|
-
} finally {
|
|
1388
|
-
await pool.end();
|
|
1389
|
-
}
|
|
1390
|
-
}
|
|
1391
|
-
/**
|
|
1392
|
-
* Mark missing migrations as applied for all tenants
|
|
1393
|
-
*
|
|
1394
|
-
* Processes all tenants in parallel with configurable concurrency.
|
|
1395
|
-
* Supports progress callbacks and abort-on-error behavior.
|
|
1396
|
-
*
|
|
1397
|
-
* @param options - Sync options
|
|
1398
|
-
* @returns Aggregate results of all mark operations
|
|
1399
|
-
*
|
|
1400
|
-
* @example
|
|
1401
|
-
* ```typescript
|
|
1402
|
-
* const results = await syncManager.markAllMissing({
|
|
1403
|
-
* concurrency: 10,
|
|
1404
|
-
* onProgress: (id, status) => console.log(`${id}: ${status}`),
|
|
1405
|
-
* });
|
|
1406
|
-
* console.log(`Succeeded: ${results.succeeded}/${results.total}`);
|
|
1407
|
-
* ```
|
|
1408
|
-
*/
|
|
1409
|
-
async markAllMissing(options = {}) {
|
|
1410
|
-
const { concurrency = 10, onProgress, onError } = options;
|
|
1411
|
-
const tenantIds = await this.config.tenantDiscovery();
|
|
1412
|
-
const results = [];
|
|
1413
|
-
let aborted = false;
|
|
1414
|
-
for (let i = 0; i < tenantIds.length && !aborted; i += concurrency) {
|
|
1415
|
-
const batch = tenantIds.slice(i, i + concurrency);
|
|
1416
|
-
const batchResults = await Promise.all(
|
|
1417
|
-
batch.map(async (tenantId) => {
|
|
1418
|
-
if (aborted) {
|
|
1419
|
-
return this.createSkippedSyncResult(tenantId);
|
|
1420
|
-
}
|
|
1421
|
-
try {
|
|
1422
|
-
onProgress?.(tenantId, "starting");
|
|
1423
|
-
const result = await this.markMissing(tenantId);
|
|
1424
|
-
onProgress?.(tenantId, result.success ? "completed" : "failed");
|
|
1425
|
-
return result;
|
|
1426
|
-
} catch (error) {
|
|
1427
|
-
onProgress?.(tenantId, "failed");
|
|
1428
|
-
const action = onError?.(tenantId, error);
|
|
1429
|
-
if (action === "abort") {
|
|
1430
|
-
aborted = true;
|
|
1431
|
-
}
|
|
1432
|
-
return this.createErrorSyncResult(tenantId, error);
|
|
1433
|
-
}
|
|
1434
|
-
})
|
|
1435
|
-
);
|
|
1436
|
-
results.push(...batchResults);
|
|
1437
|
-
}
|
|
1438
|
-
return this.aggregateSyncResults(results);
|
|
1439
|
-
}
|
|
1440
|
-
/**
|
|
1441
|
-
* Remove orphan migration records for a tenant
|
|
1442
|
-
*
|
|
1443
|
-
* Deletes records from the migrations table that don't have
|
|
1444
|
-
* corresponding files on disk.
|
|
1445
|
-
*
|
|
1446
|
-
* @param tenantId - The tenant identifier
|
|
1447
|
-
* @returns Result of the clean operation
|
|
1448
|
-
*
|
|
1449
|
-
* @example
|
|
1450
|
-
* ```typescript
|
|
1451
|
-
* const result = await syncManager.cleanOrphans('tenant-123');
|
|
1452
|
-
* if (result.success) {
|
|
1453
|
-
* console.log(`Removed ${result.removedOrphans.length} orphan records`);
|
|
1454
|
-
* }
|
|
1455
|
-
* ```
|
|
1456
|
-
*/
|
|
1457
|
-
async cleanOrphans(tenantId) {
|
|
1458
|
-
const startTime = Date.now();
|
|
1459
|
-
const schemaName = this.deps.schemaNameTemplate(tenantId);
|
|
1460
|
-
const removedOrphans = [];
|
|
1461
|
-
const pool = await this.deps.createPool(schemaName);
|
|
1462
|
-
try {
|
|
1463
|
-
const syncStatus = await this.getTenantSyncStatus(tenantId);
|
|
1464
|
-
if (syncStatus.error) {
|
|
1465
|
-
return {
|
|
1466
|
-
tenantId,
|
|
1467
|
-
schemaName,
|
|
1468
|
-
success: false,
|
|
1469
|
-
markedMigrations: [],
|
|
1470
|
-
removedOrphans: [],
|
|
1471
|
-
error: syncStatus.error,
|
|
1472
|
-
durationMs: Date.now() - startTime
|
|
1473
|
-
};
|
|
1474
|
-
}
|
|
1475
|
-
if (syncStatus.orphans.length === 0) {
|
|
1476
|
-
return {
|
|
1477
|
-
tenantId,
|
|
1478
|
-
schemaName,
|
|
1479
|
-
success: true,
|
|
1480
|
-
markedMigrations: [],
|
|
1481
|
-
removedOrphans: [],
|
|
1482
|
-
durationMs: Date.now() - startTime
|
|
1483
|
-
};
|
|
1484
|
-
}
|
|
1485
|
-
const format = await this.deps.getOrDetectFormat(pool, schemaName);
|
|
1486
|
-
const identifierColumn = format.columns.identifier;
|
|
1487
|
-
for (const orphan of syncStatus.orphans) {
|
|
1488
|
-
await pool.query(
|
|
1489
|
-
`DELETE FROM "${schemaName}"."${format.tableName}" WHERE "${identifierColumn}" = $1`,
|
|
1490
|
-
[orphan]
|
|
1491
|
-
);
|
|
1492
|
-
removedOrphans.push(orphan);
|
|
1493
|
-
}
|
|
1494
|
-
return {
|
|
1495
|
-
tenantId,
|
|
1496
|
-
schemaName,
|
|
1497
|
-
success: true,
|
|
1498
|
-
markedMigrations: [],
|
|
1499
|
-
removedOrphans,
|
|
1500
|
-
durationMs: Date.now() - startTime
|
|
1501
|
-
};
|
|
1502
|
-
} catch (error) {
|
|
1503
|
-
return {
|
|
1504
|
-
tenantId,
|
|
1505
|
-
schemaName,
|
|
1506
|
-
success: false,
|
|
1507
|
-
markedMigrations: [],
|
|
1508
|
-
removedOrphans,
|
|
1509
|
-
error: error.message,
|
|
1510
|
-
durationMs: Date.now() - startTime
|
|
1511
|
-
};
|
|
1512
|
-
} finally {
|
|
1513
|
-
await pool.end();
|
|
1514
|
-
}
|
|
1515
|
-
}
|
|
1516
|
-
/**
|
|
1517
|
-
* Remove orphan migration records for all tenants
|
|
1518
|
-
*
|
|
1519
|
-
* Processes all tenants in parallel with configurable concurrency.
|
|
1520
|
-
* Supports progress callbacks and abort-on-error behavior.
|
|
1521
|
-
*
|
|
1522
|
-
* @param options - Sync options
|
|
1523
|
-
* @returns Aggregate results of all clean operations
|
|
1524
|
-
*
|
|
1525
|
-
* @example
|
|
1526
|
-
* ```typescript
|
|
1527
|
-
* const results = await syncManager.cleanAllOrphans({
|
|
1528
|
-
* concurrency: 10,
|
|
1529
|
-
* onProgress: (id, status) => console.log(`${id}: ${status}`),
|
|
1530
|
-
* });
|
|
1531
|
-
* console.log(`Succeeded: ${results.succeeded}/${results.total}`);
|
|
1532
|
-
* ```
|
|
1533
|
-
*/
|
|
1534
|
-
async cleanAllOrphans(options = {}) {
|
|
1535
|
-
const { concurrency = 10, onProgress, onError } = options;
|
|
1536
|
-
const tenantIds = await this.config.tenantDiscovery();
|
|
1537
|
-
const results = [];
|
|
1538
|
-
let aborted = false;
|
|
1539
|
-
for (let i = 0; i < tenantIds.length && !aborted; i += concurrency) {
|
|
1540
|
-
const batch = tenantIds.slice(i, i + concurrency);
|
|
1541
|
-
const batchResults = await Promise.all(
|
|
1542
|
-
batch.map(async (tenantId) => {
|
|
1543
|
-
if (aborted) {
|
|
1544
|
-
return this.createSkippedSyncResult(tenantId);
|
|
1545
|
-
}
|
|
1546
|
-
try {
|
|
1547
|
-
onProgress?.(tenantId, "starting");
|
|
1548
|
-
const result = await this.cleanOrphans(tenantId);
|
|
1549
|
-
onProgress?.(tenantId, result.success ? "completed" : "failed");
|
|
1550
|
-
return result;
|
|
1551
|
-
} catch (error) {
|
|
1552
|
-
onProgress?.(tenantId, "failed");
|
|
1553
|
-
const action = onError?.(tenantId, error);
|
|
1554
|
-
if (action === "abort") {
|
|
1555
|
-
aborted = true;
|
|
1556
|
-
}
|
|
1557
|
-
return this.createErrorSyncResult(tenantId, error);
|
|
1558
|
-
}
|
|
1559
|
-
})
|
|
1560
|
-
);
|
|
1561
|
-
results.push(...batchResults);
|
|
1562
|
-
}
|
|
1563
|
-
return this.aggregateSyncResults(results);
|
|
1564
|
-
}
|
|
1565
|
-
// ============================================================================
|
|
1566
|
-
// Private Helper Methods
|
|
1567
|
-
// ============================================================================
|
|
1568
|
-
/**
|
|
1569
|
-
* Get applied migrations for a schema
|
|
1570
|
-
*/
|
|
1571
|
-
async getAppliedMigrations(pool, schemaName, format) {
|
|
1572
|
-
const identifierColumn = format.columns.identifier;
|
|
1573
|
-
const timestampColumn = format.columns.timestamp;
|
|
1574
|
-
const result = await pool.query(
|
|
1575
|
-
`SELECT id, "${identifierColumn}" as identifier, "${timestampColumn}" as applied_at
|
|
1576
|
-
FROM "${schemaName}"."${format.tableName}"
|
|
1577
|
-
ORDER BY id`
|
|
1578
|
-
);
|
|
1579
|
-
return result.rows.map((row) => {
|
|
1580
|
-
const appliedAt = format.columns.timestampType === "bigint" ? new Date(Number(row.applied_at)) : new Date(row.applied_at);
|
|
1581
|
-
return {
|
|
1582
|
-
identifier: row.identifier,
|
|
1583
|
-
appliedAt
|
|
1584
|
-
};
|
|
1585
|
-
});
|
|
1586
|
-
}
|
|
1587
|
-
/**
|
|
1588
|
-
* Check if a migration has been applied
|
|
1589
|
-
*/
|
|
1590
|
-
isMigrationApplied(migration, appliedIdentifiers, format) {
|
|
1591
|
-
if (format.columns.identifier === "name") {
|
|
1592
|
-
return appliedIdentifiers.has(migration.name);
|
|
1593
|
-
}
|
|
1594
|
-
return appliedIdentifiers.has(migration.hash) || appliedIdentifiers.has(migration.name);
|
|
1595
|
-
}
|
|
1596
|
-
/**
|
|
1597
|
-
* Record a migration as applied (without executing SQL)
|
|
1598
|
-
*/
|
|
1599
|
-
async recordMigration(pool, schemaName, migration, format) {
|
|
1600
|
-
const { identifier, timestamp, timestampType } = format.columns;
|
|
1601
|
-
const identifierValue = identifier === "name" ? migration.name : migration.hash;
|
|
1602
|
-
const timestampValue = timestampType === "bigint" ? Date.now() : /* @__PURE__ */ new Date();
|
|
1603
|
-
await pool.query(
|
|
1604
|
-
`INSERT INTO "${schemaName}"."${format.tableName}" ("${identifier}", "${timestamp}") VALUES ($1, $2)`,
|
|
1605
|
-
[identifierValue, timestampValue]
|
|
1606
|
-
);
|
|
1607
|
-
}
|
|
1608
|
-
/**
|
|
1609
|
-
* Create a skipped sync result for aborted operations
|
|
1610
|
-
*/
|
|
1611
|
-
createSkippedSyncResult(tenantId) {
|
|
1612
|
-
return {
|
|
1613
|
-
tenantId,
|
|
1614
|
-
schemaName: this.deps.schemaNameTemplate(tenantId),
|
|
1615
|
-
success: false,
|
|
1616
|
-
markedMigrations: [],
|
|
1617
|
-
removedOrphans: [],
|
|
1618
|
-
error: "Skipped due to abort",
|
|
1619
|
-
durationMs: 0
|
|
1620
|
-
};
|
|
1621
|
-
}
|
|
1622
|
-
/**
|
|
1623
|
-
* Create an error sync result for failed operations
|
|
1624
|
-
*/
|
|
1625
|
-
createErrorSyncResult(tenantId, error) {
|
|
1626
|
-
return {
|
|
1627
|
-
tenantId,
|
|
1628
|
-
schemaName: this.deps.schemaNameTemplate(tenantId),
|
|
1629
|
-
success: false,
|
|
1630
|
-
markedMigrations: [],
|
|
1631
|
-
removedOrphans: [],
|
|
1632
|
-
error: error.message,
|
|
1633
|
-
durationMs: 0
|
|
1634
|
-
};
|
|
1635
|
-
}
|
|
1636
|
-
/**
|
|
1637
|
-
* Aggregate individual sync results into a summary
|
|
1638
|
-
*/
|
|
1639
|
-
aggregateSyncResults(results) {
|
|
1640
|
-
return {
|
|
1641
|
-
total: results.length,
|
|
1642
|
-
succeeded: results.filter((r) => r.success).length,
|
|
1643
|
-
failed: results.filter((r) => !r.success).length,
|
|
1644
|
-
details: results
|
|
1645
|
-
};
|
|
1646
|
-
}
|
|
1647
|
-
};
|
|
1648
|
-
function createSyncManager(config, dependencies) {
|
|
1649
|
-
return new SyncManager(config, dependencies);
|
|
1650
|
-
}
|
|
1651
|
-
|
|
1652
|
-
// src/migrator/executor/migration-executor.ts
|
|
1653
|
-
var MigrationExecutor = class {
|
|
1654
|
-
constructor(config, deps) {
|
|
1655
|
-
this.config = config;
|
|
1656
|
-
this.deps = deps;
|
|
1657
|
-
}
|
|
1658
|
-
/**
|
|
1659
|
-
* Migrate a single tenant
|
|
1660
|
-
*
|
|
1661
|
-
* Applies all pending migrations to the tenant's schema.
|
|
1662
|
-
* Creates the migrations table if it doesn't exist.
|
|
1663
|
-
*
|
|
1664
|
-
* @param tenantId - The tenant identifier
|
|
1665
|
-
* @param migrations - Optional pre-loaded migrations (avoids reloading from disk)
|
|
1666
|
-
* @param options - Migration options (dryRun, onProgress)
|
|
1667
|
-
* @returns Migration result with applied migrations and duration
|
|
1668
|
-
*
|
|
1669
|
-
* @example
|
|
1670
|
-
* ```typescript
|
|
1671
|
-
* const result = await executor.migrateTenant('tenant-123', undefined, {
|
|
1672
|
-
* dryRun: false,
|
|
1673
|
-
* onProgress: (id, status, name) => console.log(`${id}: ${status} ${name}`),
|
|
1674
|
-
* });
|
|
1675
|
-
*
|
|
1676
|
-
* if (result.success) {
|
|
1677
|
-
* console.log(`Applied ${result.appliedMigrations.length} migrations`);
|
|
1678
|
-
* }
|
|
1679
|
-
* ```
|
|
1680
|
-
*/
|
|
1681
|
-
async migrateTenant(tenantId, migrations, options = {}) {
|
|
1682
|
-
const startTime = Date.now();
|
|
1683
|
-
const schemaName = this.deps.schemaNameTemplate(tenantId);
|
|
1684
|
-
const appliedMigrations = [];
|
|
1685
|
-
const pool = await this.deps.createPool(schemaName);
|
|
1686
|
-
try {
|
|
1687
|
-
await this.config.hooks?.beforeTenant?.(tenantId);
|
|
1688
|
-
const format = await this.deps.getOrDetectFormat(pool, schemaName);
|
|
1689
|
-
await this.deps.ensureMigrationsTable(pool, schemaName, format);
|
|
1690
|
-
const allMigrations = migrations ?? await this.deps.loadMigrations();
|
|
1691
|
-
const applied = await this.getAppliedMigrations(pool, schemaName, format);
|
|
1692
|
-
const appliedSet = new Set(applied.map((m) => m.identifier));
|
|
1693
|
-
const pending = allMigrations.filter(
|
|
1694
|
-
(m) => !this.isMigrationApplied(m, appliedSet, format)
|
|
1695
|
-
);
|
|
1696
|
-
if (options.dryRun) {
|
|
1697
|
-
return {
|
|
1698
|
-
tenantId,
|
|
1699
|
-
schemaName,
|
|
1700
|
-
success: true,
|
|
1701
|
-
appliedMigrations: pending.map((m) => m.name),
|
|
1702
|
-
durationMs: Date.now() - startTime,
|
|
1703
|
-
format: format.format
|
|
1704
|
-
};
|
|
1705
|
-
}
|
|
1706
|
-
for (const migration of pending) {
|
|
1707
|
-
const migrationStart = Date.now();
|
|
1708
|
-
options.onProgress?.(tenantId, "migrating", migration.name);
|
|
1709
|
-
await this.config.hooks?.beforeMigration?.(tenantId, migration.name);
|
|
1710
|
-
await this.applyMigration(pool, schemaName, migration, format);
|
|
1711
|
-
await this.config.hooks?.afterMigration?.(
|
|
1712
|
-
tenantId,
|
|
1713
|
-
migration.name,
|
|
1714
|
-
Date.now() - migrationStart
|
|
1715
|
-
);
|
|
1716
|
-
appliedMigrations.push(migration.name);
|
|
1717
|
-
}
|
|
1718
|
-
const result = {
|
|
1719
|
-
tenantId,
|
|
1720
|
-
schemaName,
|
|
1721
|
-
success: true,
|
|
1722
|
-
appliedMigrations,
|
|
1723
|
-
durationMs: Date.now() - startTime,
|
|
1724
|
-
format: format.format
|
|
1725
|
-
};
|
|
1726
|
-
await this.config.hooks?.afterTenant?.(tenantId, result);
|
|
1727
|
-
return result;
|
|
1728
|
-
} catch (error) {
|
|
1729
|
-
const result = {
|
|
1730
|
-
tenantId,
|
|
1731
|
-
schemaName,
|
|
1732
|
-
success: false,
|
|
1733
|
-
appliedMigrations,
|
|
1734
|
-
error: error.message,
|
|
1735
|
-
durationMs: Date.now() - startTime
|
|
1736
|
-
};
|
|
1737
|
-
await this.config.hooks?.afterTenant?.(tenantId, result);
|
|
1738
|
-
return result;
|
|
1739
|
-
} finally {
|
|
1740
|
-
await pool.end();
|
|
1741
|
-
}
|
|
1742
|
-
}
|
|
1743
|
-
/**
|
|
1744
|
-
* Mark migrations as applied without executing SQL
|
|
1745
|
-
*
|
|
1746
|
-
* Useful for syncing tracking state with already-applied migrations
|
|
1747
|
-
* or when migrations were applied manually.
|
|
1748
|
-
*
|
|
1749
|
-
* @param tenantId - The tenant identifier
|
|
1750
|
-
* @param options - Options with progress callback
|
|
1751
|
-
* @returns Result with list of marked migrations
|
|
1752
|
-
*
|
|
1753
|
-
* @example
|
|
1754
|
-
* ```typescript
|
|
1755
|
-
* const result = await executor.markAsApplied('tenant-123', {
|
|
1756
|
-
* onProgress: (id, status, name) => console.log(`${id}: marking ${name}`),
|
|
1757
|
-
* });
|
|
1758
|
-
*
|
|
1759
|
-
* console.log(`Marked ${result.appliedMigrations.length} migrations`);
|
|
1760
|
-
* ```
|
|
1761
|
-
*/
|
|
1762
|
-
async markAsApplied(tenantId, options = {}) {
|
|
1763
|
-
const startTime = Date.now();
|
|
1764
|
-
const schemaName = this.deps.schemaNameTemplate(tenantId);
|
|
1765
|
-
const markedMigrations = [];
|
|
1766
|
-
const pool = await this.deps.createPool(schemaName);
|
|
1767
|
-
try {
|
|
1768
|
-
await this.config.hooks?.beforeTenant?.(tenantId);
|
|
1769
|
-
const format = await this.deps.getOrDetectFormat(pool, schemaName);
|
|
1770
|
-
await this.deps.ensureMigrationsTable(pool, schemaName, format);
|
|
1771
|
-
const allMigrations = await this.deps.loadMigrations();
|
|
1772
|
-
const applied = await this.getAppliedMigrations(pool, schemaName, format);
|
|
1773
|
-
const appliedSet = new Set(applied.map((m) => m.identifier));
|
|
1774
|
-
const pending = allMigrations.filter(
|
|
1775
|
-
(m) => !this.isMigrationApplied(m, appliedSet, format)
|
|
1776
|
-
);
|
|
1777
|
-
for (const migration of pending) {
|
|
1778
|
-
const migrationStart = Date.now();
|
|
1779
|
-
options.onProgress?.(tenantId, "migrating", migration.name);
|
|
1780
|
-
await this.config.hooks?.beforeMigration?.(tenantId, migration.name);
|
|
1781
|
-
await this.recordMigration(pool, schemaName, migration, format);
|
|
1782
|
-
await this.config.hooks?.afterMigration?.(
|
|
1783
|
-
tenantId,
|
|
1784
|
-
migration.name,
|
|
1785
|
-
Date.now() - migrationStart
|
|
1786
|
-
);
|
|
1787
|
-
markedMigrations.push(migration.name);
|
|
1788
|
-
}
|
|
1789
|
-
const result = {
|
|
1790
|
-
tenantId,
|
|
1791
|
-
schemaName,
|
|
1792
|
-
success: true,
|
|
1793
|
-
appliedMigrations: markedMigrations,
|
|
1794
|
-
durationMs: Date.now() - startTime,
|
|
1795
|
-
format: format.format
|
|
1796
|
-
};
|
|
1797
|
-
await this.config.hooks?.afterTenant?.(tenantId, result);
|
|
1798
|
-
return result;
|
|
1799
|
-
} catch (error) {
|
|
1800
|
-
const result = {
|
|
1801
|
-
tenantId,
|
|
1802
|
-
schemaName,
|
|
1803
|
-
success: false,
|
|
1804
|
-
appliedMigrations: markedMigrations,
|
|
1805
|
-
error: error.message,
|
|
1806
|
-
durationMs: Date.now() - startTime
|
|
1807
|
-
};
|
|
1808
|
-
await this.config.hooks?.afterTenant?.(tenantId, result);
|
|
1809
|
-
return result;
|
|
1810
|
-
} finally {
|
|
1811
|
-
await pool.end();
|
|
1812
|
-
}
|
|
1813
|
-
}
|
|
1814
|
-
/**
|
|
1815
|
-
* Get migration status for a specific tenant
|
|
1816
|
-
*
|
|
1817
|
-
* Returns information about applied and pending migrations.
|
|
1818
|
-
*
|
|
1819
|
-
* @param tenantId - The tenant identifier
|
|
1820
|
-
* @param migrations - Optional pre-loaded migrations
|
|
1821
|
-
* @returns Migration status with counts and pending list
|
|
1822
|
-
*
|
|
1823
|
-
* @example
|
|
1824
|
-
* ```typescript
|
|
1825
|
-
* const status = await executor.getTenantStatus('tenant-123');
|
|
1826
|
-
* if (status.status === 'behind') {
|
|
1827
|
-
* console.log(`Pending: ${status.pendingMigrations.join(', ')}`);
|
|
1828
|
-
* }
|
|
1829
|
-
* ```
|
|
1830
|
-
*/
|
|
1831
|
-
async getTenantStatus(tenantId, migrations) {
|
|
1832
|
-
const schemaName = this.deps.schemaNameTemplate(tenantId);
|
|
1833
|
-
const pool = await this.deps.createPool(schemaName);
|
|
1834
|
-
try {
|
|
1835
|
-
const allMigrations = migrations ?? await this.deps.loadMigrations();
|
|
1836
|
-
const tableExists = await this.deps.migrationsTableExists(pool, schemaName);
|
|
1837
|
-
if (!tableExists) {
|
|
1838
|
-
return {
|
|
1839
|
-
tenantId,
|
|
1840
|
-
schemaName,
|
|
1841
|
-
appliedCount: 0,
|
|
1842
|
-
pendingCount: allMigrations.length,
|
|
1843
|
-
pendingMigrations: allMigrations.map((m) => m.name),
|
|
1844
|
-
status: allMigrations.length > 0 ? "behind" : "ok",
|
|
1845
|
-
format: null
|
|
1846
|
-
};
|
|
1847
|
-
}
|
|
1848
|
-
const format = await this.deps.getOrDetectFormat(pool, schemaName);
|
|
1849
|
-
const applied = await this.getAppliedMigrations(pool, schemaName, format);
|
|
1850
|
-
const appliedSet = new Set(applied.map((m) => m.identifier));
|
|
1851
|
-
const pending = allMigrations.filter(
|
|
1852
|
-
(m) => !this.isMigrationApplied(m, appliedSet, format)
|
|
1853
|
-
);
|
|
1854
|
-
return {
|
|
1855
|
-
tenantId,
|
|
1856
|
-
schemaName,
|
|
1857
|
-
appliedCount: applied.length,
|
|
1858
|
-
pendingCount: pending.length,
|
|
1859
|
-
pendingMigrations: pending.map((m) => m.name),
|
|
1860
|
-
status: pending.length > 0 ? "behind" : "ok",
|
|
1861
|
-
format: format.format
|
|
1862
|
-
};
|
|
1863
|
-
} catch (error) {
|
|
1864
|
-
return {
|
|
1865
|
-
tenantId,
|
|
1866
|
-
schemaName,
|
|
1867
|
-
appliedCount: 0,
|
|
1868
|
-
pendingCount: 0,
|
|
1869
|
-
pendingMigrations: [],
|
|
1870
|
-
status: "error",
|
|
1871
|
-
error: error.message,
|
|
1872
|
-
format: null
|
|
1873
|
-
};
|
|
1874
|
-
} finally {
|
|
1875
|
-
await pool.end();
|
|
1876
|
-
}
|
|
1877
|
-
}
|
|
1878
|
-
// ============================================================================
|
|
1879
|
-
// IMigrationExecutor Interface Methods
|
|
1880
|
-
// ============================================================================
|
|
1881
|
-
/**
|
|
1882
|
-
* Execute a single migration on a schema
|
|
1883
|
-
*/
|
|
1884
|
-
async executeMigration(pool, schemaName, migration, format, options) {
|
|
1885
|
-
if (options?.markOnly) {
|
|
1886
|
-
options.onProgress?.("recording");
|
|
1887
|
-
await this.recordMigration(pool, schemaName, migration, format);
|
|
1888
|
-
} else {
|
|
1889
|
-
options?.onProgress?.("applying");
|
|
1890
|
-
await this.applyMigration(pool, schemaName, migration, format);
|
|
1891
|
-
}
|
|
1892
|
-
}
|
|
1893
|
-
/**
|
|
1894
|
-
* Execute multiple migrations on a schema
|
|
1895
|
-
*/
|
|
1896
|
-
async executeMigrations(pool, schemaName, migrations, format, options) {
|
|
1897
|
-
const appliedNames = [];
|
|
1898
|
-
for (const migration of migrations) {
|
|
1899
|
-
await this.executeMigration(pool, schemaName, migration, format, options);
|
|
1900
|
-
appliedNames.push(migration.name);
|
|
1901
|
-
}
|
|
1902
|
-
return appliedNames;
|
|
1903
|
-
}
|
|
1904
|
-
/**
|
|
1905
|
-
* Record a migration as applied without executing SQL
|
|
1906
|
-
*/
|
|
1907
|
-
async recordMigration(pool, schemaName, migration, format) {
|
|
1908
|
-
const { identifier, timestamp, timestampType } = format.columns;
|
|
1909
|
-
const identifierValue = identifier === "name" ? migration.name : migration.hash;
|
|
1910
|
-
const timestampValue = timestampType === "bigint" ? Date.now() : /* @__PURE__ */ new Date();
|
|
1911
|
-
await pool.query(
|
|
1912
|
-
`INSERT INTO "${schemaName}"."${format.tableName}" ("${identifier}", "${timestamp}") VALUES ($1, $2)`,
|
|
1913
|
-
[identifierValue, timestampValue]
|
|
1914
|
-
);
|
|
1915
|
-
}
|
|
1916
|
-
/**
|
|
1917
|
-
* Get list of applied migrations for a tenant
|
|
1918
|
-
*/
|
|
1919
|
-
async getAppliedMigrations(pool, schemaName, format) {
|
|
1920
|
-
const identifierColumn = format.columns.identifier;
|
|
1921
|
-
const timestampColumn = format.columns.timestamp;
|
|
1922
|
-
const result = await pool.query(
|
|
1923
|
-
`SELECT id, "${identifierColumn}" as identifier, "${timestampColumn}" as applied_at
|
|
1924
|
-
FROM "${schemaName}"."${format.tableName}"
|
|
1925
|
-
ORDER BY id`
|
|
1926
|
-
);
|
|
1927
|
-
return result.rows.map((row) => {
|
|
1928
|
-
const appliedAt = format.columns.timestampType === "bigint" ? new Date(Number(row.applied_at)) : new Date(row.applied_at);
|
|
1929
|
-
return {
|
|
1930
|
-
identifier: row.identifier,
|
|
1931
|
-
// Set name or hash based on format
|
|
1932
|
-
...format.columns.identifier === "name" ? { name: row.identifier } : { hash: row.identifier },
|
|
1933
|
-
appliedAt
|
|
1934
|
-
};
|
|
1935
|
-
});
|
|
1936
|
-
}
|
|
1937
|
-
/**
|
|
1938
|
-
* Get pending migrations (not yet applied)
|
|
1939
|
-
*/
|
|
1940
|
-
async getPendingMigrations(pool, schemaName, allMigrations, format) {
|
|
1941
|
-
const applied = await this.getAppliedMigrations(pool, schemaName, format);
|
|
1942
|
-
const appliedSet = new Set(applied.map((m) => m.identifier));
|
|
1943
|
-
return allMigrations.filter(
|
|
1944
|
-
(m) => !this.isMigrationApplied(m, appliedSet, format)
|
|
1945
|
-
);
|
|
1946
|
-
}
|
|
1947
|
-
// ============================================================================
|
|
1948
|
-
// Private Helper Methods
|
|
1949
|
-
// ============================================================================
|
|
1950
|
-
/**
|
|
1951
|
-
* Check if a migration has been applied
|
|
1952
|
-
*/
|
|
1953
|
-
isMigrationApplied(migration, appliedIdentifiers, format) {
|
|
1954
|
-
if (format.columns.identifier === "name") {
|
|
1955
|
-
return appliedIdentifiers.has(migration.name);
|
|
1956
|
-
}
|
|
1957
|
-
return appliedIdentifiers.has(migration.hash) || appliedIdentifiers.has(migration.name);
|
|
1958
|
-
}
|
|
1959
|
-
/**
|
|
1960
|
-
* Apply a migration to a schema (execute SQL + record)
|
|
1961
|
-
*/
|
|
1962
|
-
async applyMigration(pool, schemaName, migration, format) {
|
|
1963
|
-
const client = await pool.connect();
|
|
1964
|
-
try {
|
|
1965
|
-
await client.query("BEGIN");
|
|
1966
|
-
await client.query(migration.sql);
|
|
1967
|
-
const { identifier, timestamp, timestampType } = format.columns;
|
|
1968
|
-
const identifierValue = identifier === "name" ? migration.name : migration.hash;
|
|
1969
|
-
const timestampValue = timestampType === "bigint" ? Date.now() : /* @__PURE__ */ new Date();
|
|
1970
|
-
await client.query(
|
|
1971
|
-
`INSERT INTO "${schemaName}"."${format.tableName}" ("${identifier}", "${timestamp}") VALUES ($1, $2)`,
|
|
1972
|
-
[identifierValue, timestampValue]
|
|
1973
|
-
);
|
|
1974
|
-
await client.query("COMMIT");
|
|
1975
|
-
} catch (error) {
|
|
1976
|
-
await client.query("ROLLBACK");
|
|
1977
|
-
throw error;
|
|
1978
|
-
} finally {
|
|
1979
|
-
client.release();
|
|
1980
|
-
}
|
|
1981
|
-
}
|
|
1982
|
-
};
|
|
1983
|
-
function createMigrationExecutor(config, dependencies) {
|
|
1984
|
-
return new MigrationExecutor(config, dependencies);
|
|
1985
|
-
}
|
|
1986
|
-
|
|
1987
|
-
// src/migrator/executor/batch-executor.ts
|
|
1988
|
-
var BatchExecutor = class {
|
|
1989
|
-
constructor(config, executor, loadMigrations) {
|
|
1990
|
-
this.config = config;
|
|
1991
|
-
this.executor = executor;
|
|
1992
|
-
this.loadMigrations = loadMigrations;
|
|
1993
|
-
}
|
|
1994
|
-
/**
|
|
1995
|
-
* Migrate all tenants in parallel
|
|
1996
|
-
*
|
|
1997
|
-
* Processes tenants in batches with configurable concurrency.
|
|
1998
|
-
* Supports progress callbacks, error handling, and abort behavior.
|
|
1999
|
-
*
|
|
2000
|
-
* @param options - Migration options (concurrency, dryRun, callbacks)
|
|
2001
|
-
* @returns Aggregate results for all tenants
|
|
2002
|
-
*
|
|
2003
|
-
* @example
|
|
2004
|
-
* ```typescript
|
|
2005
|
-
* const results = await batchExecutor.migrateAll({
|
|
2006
|
-
* concurrency: 10,
|
|
2007
|
-
* dryRun: false,
|
|
2008
|
-
* onProgress: (id, status) => console.log(`${id}: ${status}`),
|
|
2009
|
-
* onError: (id, error) => {
|
|
2010
|
-
* console.error(`${id} failed: ${error.message}`);
|
|
2011
|
-
* return 'continue'; // or 'abort' to stop all
|
|
2012
|
-
* },
|
|
2013
|
-
* });
|
|
2014
|
-
*
|
|
2015
|
-
* console.log(`Succeeded: ${results.succeeded}/${results.total}`);
|
|
2016
|
-
* ```
|
|
2017
|
-
*/
|
|
2018
|
-
async migrateAll(options = {}) {
|
|
2019
|
-
const {
|
|
2020
|
-
concurrency = 10,
|
|
2021
|
-
onProgress,
|
|
2022
|
-
onError,
|
|
2023
|
-
dryRun = false
|
|
2024
|
-
} = options;
|
|
2025
|
-
const tenantIds = await this.config.tenantDiscovery();
|
|
2026
|
-
const migrations = await this.loadMigrations();
|
|
2027
|
-
const results = [];
|
|
2028
|
-
let aborted = false;
|
|
2029
|
-
for (let i = 0; i < tenantIds.length && !aborted; i += concurrency) {
|
|
2030
|
-
const batch = tenantIds.slice(i, i + concurrency);
|
|
2031
|
-
const batchResults = await Promise.all(
|
|
2032
|
-
batch.map(async (tenantId) => {
|
|
2033
|
-
if (aborted) {
|
|
2034
|
-
return this.createSkippedResult(tenantId);
|
|
2035
|
-
}
|
|
2036
|
-
try {
|
|
2037
|
-
onProgress?.(tenantId, "starting");
|
|
2038
|
-
const result = await this.executor.migrateTenant(tenantId, migrations, { dryRun, onProgress });
|
|
2039
|
-
onProgress?.(tenantId, result.success ? "completed" : "failed");
|
|
2040
|
-
return result;
|
|
2041
|
-
} catch (error) {
|
|
2042
|
-
onProgress?.(tenantId, "failed");
|
|
2043
|
-
const action = onError?.(tenantId, error);
|
|
2044
|
-
if (action === "abort") {
|
|
2045
|
-
aborted = true;
|
|
2046
|
-
}
|
|
2047
|
-
return this.createErrorResult(tenantId, error);
|
|
2048
|
-
}
|
|
2049
|
-
})
|
|
2050
|
-
);
|
|
2051
|
-
results.push(...batchResults);
|
|
2052
|
-
}
|
|
2053
|
-
if (aborted) {
|
|
2054
|
-
const remaining = tenantIds.slice(results.length);
|
|
2055
|
-
for (const tenantId of remaining) {
|
|
2056
|
-
results.push(this.createSkippedResult(tenantId));
|
|
2057
|
-
}
|
|
2058
|
-
}
|
|
2059
|
-
return this.aggregateResults(results);
|
|
2060
|
-
}
|
|
2061
|
-
/**
|
|
2062
|
-
* Migrate specific tenants in parallel
|
|
2063
|
-
*
|
|
2064
|
-
* Same as migrateAll but for a subset of tenants.
|
|
2065
|
-
*
|
|
2066
|
-
* @param tenantIds - List of tenant IDs to migrate
|
|
2067
|
-
* @param options - Migration options
|
|
2068
|
-
* @returns Aggregate results for specified tenants
|
|
2069
|
-
*
|
|
2070
|
-
* @example
|
|
2071
|
-
* ```typescript
|
|
2072
|
-
* const results = await batchExecutor.migrateTenants(
|
|
2073
|
-
* ['tenant-1', 'tenant-2', 'tenant-3'],
|
|
2074
|
-
* { concurrency: 5 }
|
|
2075
|
-
* );
|
|
2076
|
-
* ```
|
|
2077
|
-
*/
|
|
2078
|
-
async migrateTenants(tenantIds, options = {}) {
|
|
2079
|
-
const migrations = await this.loadMigrations();
|
|
2080
|
-
const results = [];
|
|
2081
|
-
const { concurrency = 10, onProgress, onError, dryRun = false } = options;
|
|
2082
|
-
for (let i = 0; i < tenantIds.length; i += concurrency) {
|
|
2083
|
-
const batch = tenantIds.slice(i, i + concurrency);
|
|
2084
|
-
const batchResults = await Promise.all(
|
|
2085
|
-
batch.map(async (tenantId) => {
|
|
2086
|
-
try {
|
|
2087
|
-
onProgress?.(tenantId, "starting");
|
|
2088
|
-
const result = await this.executor.migrateTenant(tenantId, migrations, { dryRun, onProgress });
|
|
2089
|
-
onProgress?.(tenantId, result.success ? "completed" : "failed");
|
|
2090
|
-
return result;
|
|
2091
|
-
} catch (error) {
|
|
2092
|
-
onProgress?.(tenantId, "failed");
|
|
2093
|
-
onError?.(tenantId, error);
|
|
2094
|
-
return this.createErrorResult(tenantId, error);
|
|
2095
|
-
}
|
|
2096
|
-
})
|
|
2097
|
-
);
|
|
2098
|
-
results.push(...batchResults);
|
|
2099
|
-
}
|
|
2100
|
-
return this.aggregateResults(results);
|
|
2101
|
-
}
|
|
2102
|
-
/**
|
|
2103
|
-
* Mark all tenants as applied without executing SQL
|
|
2104
|
-
*
|
|
2105
|
-
* Useful for syncing tracking state with already-applied migrations.
|
|
2106
|
-
* Processes tenants in parallel with configurable concurrency.
|
|
2107
|
-
*
|
|
2108
|
-
* @param options - Migration options
|
|
2109
|
-
* @returns Aggregate results for all tenants
|
|
2110
|
-
*
|
|
2111
|
-
* @example
|
|
2112
|
-
* ```typescript
|
|
2113
|
-
* const results = await batchExecutor.markAllAsApplied({
|
|
2114
|
-
* concurrency: 10,
|
|
2115
|
-
* onProgress: (id, status) => console.log(`${id}: ${status}`),
|
|
2116
|
-
* });
|
|
2117
|
-
* ```
|
|
2118
|
-
*/
|
|
2119
|
-
async markAllAsApplied(options = {}) {
|
|
2120
|
-
const {
|
|
2121
|
-
concurrency = 10,
|
|
2122
|
-
onProgress,
|
|
2123
|
-
onError
|
|
2124
|
-
} = options;
|
|
2125
|
-
const tenantIds = await this.config.tenantDiscovery();
|
|
2126
|
-
const results = [];
|
|
2127
|
-
let aborted = false;
|
|
2128
|
-
for (let i = 0; i < tenantIds.length && !aborted; i += concurrency) {
|
|
2129
|
-
const batch = tenantIds.slice(i, i + concurrency);
|
|
2130
|
-
const batchResults = await Promise.all(
|
|
2131
|
-
batch.map(async (tenantId) => {
|
|
2132
|
-
if (aborted) {
|
|
2133
|
-
return this.createSkippedResult(tenantId);
|
|
2134
|
-
}
|
|
2135
|
-
try {
|
|
2136
|
-
onProgress?.(tenantId, "starting");
|
|
2137
|
-
const result = await this.executor.markAsApplied(tenantId, { onProgress });
|
|
2138
|
-
onProgress?.(tenantId, result.success ? "completed" : "failed");
|
|
2139
|
-
return result;
|
|
2140
|
-
} catch (error) {
|
|
2141
|
-
onProgress?.(tenantId, "failed");
|
|
2142
|
-
const action = onError?.(tenantId, error);
|
|
2143
|
-
if (action === "abort") {
|
|
2144
|
-
aborted = true;
|
|
2145
|
-
}
|
|
2146
|
-
return this.createErrorResult(tenantId, error);
|
|
2147
|
-
}
|
|
2148
|
-
})
|
|
2149
|
-
);
|
|
2150
|
-
results.push(...batchResults);
|
|
2151
|
-
}
|
|
2152
|
-
if (aborted) {
|
|
2153
|
-
const remaining = tenantIds.slice(results.length);
|
|
2154
|
-
for (const tenantId of remaining) {
|
|
2155
|
-
results.push(this.createSkippedResult(tenantId));
|
|
2156
|
-
}
|
|
2157
|
-
}
|
|
2158
|
-
return this.aggregateResults(results);
|
|
2159
|
-
}
|
|
2160
|
-
/**
|
|
2161
|
-
* Get migration status for all tenants
|
|
2162
|
-
*
|
|
2163
|
-
* Queries each tenant's migration status sequentially.
|
|
2164
|
-
*
|
|
2165
|
-
* @returns List of migration status for all tenants
|
|
2166
|
-
*
|
|
2167
|
-
* @example
|
|
2168
|
-
* ```typescript
|
|
2169
|
-
* const statuses = await batchExecutor.getStatus();
|
|
2170
|
-
* const behind = statuses.filter(s => s.status === 'behind');
|
|
2171
|
-
* console.log(`${behind.length} tenants need migrations`);
|
|
2172
|
-
* ```
|
|
2173
|
-
*/
|
|
2174
|
-
async getStatus() {
|
|
2175
|
-
const tenantIds = await this.config.tenantDiscovery();
|
|
2176
|
-
const migrations = await this.loadMigrations();
|
|
2177
|
-
const statuses = [];
|
|
2178
|
-
for (const tenantId of tenantIds) {
|
|
2179
|
-
statuses.push(await this.executor.getTenantStatus(tenantId, migrations));
|
|
2180
|
-
}
|
|
2181
|
-
return statuses;
|
|
2182
|
-
}
|
|
2183
|
-
// ============================================================================
|
|
2184
|
-
// Private Helper Methods
|
|
2185
|
-
// ============================================================================
|
|
2186
|
-
/**
|
|
2187
|
-
* Create a skipped result for aborted operations
|
|
2188
|
-
*/
|
|
2189
|
-
createSkippedResult(tenantId) {
|
|
2190
|
-
return {
|
|
2191
|
-
tenantId,
|
|
2192
|
-
schemaName: "",
|
|
2193
|
-
// Schema name not available in batch context
|
|
2194
|
-
success: false,
|
|
2195
|
-
appliedMigrations: [],
|
|
2196
|
-
error: "Skipped due to abort",
|
|
2197
|
-
durationMs: 0
|
|
2198
|
-
};
|
|
2199
|
-
}
|
|
2200
|
-
/**
|
|
2201
|
-
* Create an error result for failed operations
|
|
2202
|
-
*/
|
|
2203
|
-
createErrorResult(tenantId, error) {
|
|
2204
|
-
return {
|
|
2205
|
-
tenantId,
|
|
2206
|
-
schemaName: "",
|
|
2207
|
-
// Schema name not available in batch context
|
|
2208
|
-
success: false,
|
|
2209
|
-
appliedMigrations: [],
|
|
2210
|
-
error: error.message,
|
|
2211
|
-
durationMs: 0
|
|
2212
|
-
};
|
|
2213
|
-
}
|
|
2214
|
-
/**
|
|
2215
|
-
* Aggregate individual migration results into a summary
|
|
2216
|
-
*/
|
|
2217
|
-
aggregateResults(results) {
|
|
2218
|
-
return {
|
|
2219
|
-
total: results.length,
|
|
2220
|
-
succeeded: results.filter((r) => r.success).length,
|
|
2221
|
-
failed: results.filter((r) => !r.success && r.error !== "Skipped due to abort").length,
|
|
2222
|
-
skipped: results.filter((r) => r.error === "Skipped due to abort").length,
|
|
2223
|
-
details: results
|
|
2224
|
-
};
|
|
2225
|
-
}
|
|
2226
|
-
};
|
|
2227
|
-
function createBatchExecutor(config, executor, loadMigrations) {
|
|
2228
|
-
return new BatchExecutor(config, executor, loadMigrations);
|
|
2229
|
-
}
|
|
2230
|
-
|
|
2231
|
-
// src/migrator/clone/ddl-generator.ts
|
|
2232
|
-
async function listTables(pool, schemaName, excludeTables = []) {
|
|
2233
|
-
const excludePlaceholders = excludeTables.length > 0 ? excludeTables.map((_, i) => `$${i + 2}`).join(", ") : "''::text";
|
|
2234
|
-
const result = await pool.query(
|
|
2235
|
-
`SELECT table_name
|
|
62
|
+
ORDER BY table_name`,[n]),o=[];for(let l of s.rows){if(i.includes(l.table_name))continue;let c=await v(e,n,l.table_name),u=r?await j(e,n,l.table_name):[],g=t?await B(e,n,l.table_name):[];o.push({name:l.table_name,columns:c,indexes:u,constraints:g});}return o}};var R=class{constructor(e,n){this.config=e;this.deps=n;}async seedTenant(e,n){let a=Date.now(),r=this.deps.schemaNameTemplate(e),t=await this.deps.createPool(r);try{let i=drizzle(t,{schema:this.deps.tenantSchema});return await n(i,e),{tenantId:e,schemaName:r,success:!0,durationMs:Date.now()-a}}catch(i){return {tenantId:e,schemaName:r,success:false,error:i.message,durationMs:Date.now()-a}}finally{await t.end();}}async seedAll(e,n={}){let{concurrency:a=10,onProgress:r,onError:t}=n,i=await this.config.tenantDiscovery(),s=[],o=false;for(let l=0;l<i.length&&!o;l+=a){let c=i.slice(l,l+a),u=await Promise.all(c.map(async g=>{if(o)return this.createSkippedResult(g);try{r?.(g,"starting"),r?.(g,"seeding");let p=await this.seedTenant(g,e);return r?.(g,p.success?"completed":"failed"),p}catch(p){return r?.(g,"failed"),t?.(g,p)==="abort"&&(o=true),this.createErrorResult(g,p)}}));s.push(...u);}if(o){let l=i.slice(s.length);for(let c of l)s.push(this.createSkippedResult(c));}return this.aggregateResults(s)}async seedTenants(e,n,a={}){let{concurrency:r=10,onProgress:t,onError:i}=a,s=[];for(let o=0;o<e.length;o+=r){let l=e.slice(o,o+r),c=await Promise.all(l.map(async u=>{try{t?.(u,"starting"),t?.(u,"seeding");let g=await this.seedTenant(u,n);return t?.(u,g.success?"completed":"failed"),g}catch(g){return t?.(u,"failed"),i?.(u,g),this.createErrorResult(u,g)}}));s.push(...c);}return this.aggregateResults(s)}createSkippedResult(e){return {tenantId:e,schemaName:this.deps.schemaNameTemplate(e),success:false,error:"Skipped due to abort",durationMs:0}}createErrorResult(e,n){return {tenantId:e,schemaName:this.deps.schemaNameTemplate(e),success:false,error:n.message,durationMs:0}}aggregateResults(e){return {total:e.length,succeeded:e.filter(n=>n.success).length,failed:e.filter(n=>!n.success&&n.error!=="Skipped due to abort").length,skipped:e.filter(n=>n.error==="Skipped due to abort").length,details:e}}};function ce(m,e){return new R(m,e)}var le="public",A=class{constructor(e,n){this.config=e;this.deps=n;this.schemaName=e.schemaName??le;}schemaName;async seed(e){let n=Date.now(),a=await this.deps.createPool();try{this.config.hooks?.onStart?.();let r=drizzle(a,{schema:this.deps.sharedSchema});return await e(r),this.config.hooks?.onComplete?.(),{schemaName:this.schemaName,success:!0,durationMs:Date.now()-n}}catch(r){return this.config.hooks?.onError?.(r),{schemaName:this.schemaName,success:false,error:r.message,durationMs:Date.now()-n}}finally{await a.end();}}};var x=class{constructor(e,n){this.config=e;this.deps=n;}async getSyncStatus(){let e=await this.config.tenantDiscovery(),n=await this.deps.loadMigrations(),a=[];for(let r of e)a.push(await this.getTenantSyncStatus(r,n));return {total:a.length,inSync:a.filter(r=>r.inSync&&!r.error).length,outOfSync:a.filter(r=>!r.inSync&&!r.error).length,error:a.filter(r=>!!r.error).length,details:a}}async getTenantSyncStatus(e,n){let a=this.deps.schemaNameTemplate(e),r=await this.deps.createPool(a);try{let t=n??await this.deps.loadMigrations(),i=new Set(t.map(h=>h.name)),s=new Set(t.map(h=>h.hash));if(!await this.deps.migrationsTableExists(r,a))return {tenantId:e,schemaName:a,missing:t.map(h=>h.name),orphans:[],inSync:t.length===0,format:null};let l=await this.deps.getOrDetectFormat(r,a),c=await this.getAppliedMigrations(r,a,l),u=new Set(c.map(h=>h.identifier)),g=t.filter(h=>!this.isMigrationApplied(h,u,l)).map(h=>h.name),p=c.filter(h=>(l.columns.identifier==="name"||!s.has(h.identifier))&&!i.has(h.identifier)).map(h=>h.identifier);return {tenantId:e,schemaName:a,missing:g,orphans:p,inSync:g.length===0&&p.length===0,format:l.format}}catch(t){return {tenantId:e,schemaName:a,missing:[],orphans:[],inSync:false,format:null,error:t.message}}finally{await r.end();}}async markMissing(e){let n=Date.now(),a=this.deps.schemaNameTemplate(e),r=[],t=await this.deps.createPool(a);try{let i=await this.getTenantSyncStatus(e);if(i.error)return {tenantId:e,schemaName:a,success:!1,markedMigrations:[],removedOrphans:[],error:i.error,durationMs:Date.now()-n};if(i.missing.length===0)return {tenantId:e,schemaName:a,success:!0,markedMigrations:[],removedOrphans:[],durationMs:Date.now()-n};let s=await this.deps.getOrDetectFormat(t,a);await this.deps.ensureMigrationsTable(t,a,s);let o=await this.deps.loadMigrations(),l=new Set(i.missing);for(let c of o)l.has(c.name)&&(await this.recordMigration(t,a,c,s),r.push(c.name));return {tenantId:e,schemaName:a,success:!0,markedMigrations:r,removedOrphans:[],durationMs:Date.now()-n}}catch(i){return {tenantId:e,schemaName:a,success:false,markedMigrations:r,removedOrphans:[],error:i.message,durationMs:Date.now()-n}}finally{await t.end();}}async markAllMissing(e={}){let{concurrency:n=10,onProgress:a,onError:r}=e,t=await this.config.tenantDiscovery(),i=[],s=false;for(let o=0;o<t.length&&!s;o+=n){let l=t.slice(o,o+n),c=await Promise.all(l.map(async u=>{if(s)return this.createSkippedSyncResult(u);try{a?.(u,"starting");let g=await this.markMissing(u);return a?.(u,g.success?"completed":"failed"),g}catch(g){return a?.(u,"failed"),r?.(u,g)==="abort"&&(s=true),this.createErrorSyncResult(u,g)}}));i.push(...c);}return this.aggregateSyncResults(i)}async cleanOrphans(e){let n=Date.now(),a=this.deps.schemaNameTemplate(e),r=[],t=await this.deps.createPool(a);try{let i=await this.getTenantSyncStatus(e);if(i.error)return {tenantId:e,schemaName:a,success:!1,markedMigrations:[],removedOrphans:[],error:i.error,durationMs:Date.now()-n};if(i.orphans.length===0)return {tenantId:e,schemaName:a,success:!0,markedMigrations:[],removedOrphans:[],durationMs:Date.now()-n};let s=await this.deps.getOrDetectFormat(t,a),o=s.columns.identifier;for(let l of i.orphans)await t.query(`DELETE FROM "${a}"."${s.tableName}" WHERE "${o}" = $1`,[l]),r.push(l);return {tenantId:e,schemaName:a,success:!0,markedMigrations:[],removedOrphans:r,durationMs:Date.now()-n}}catch(i){return {tenantId:e,schemaName:a,success:false,markedMigrations:[],removedOrphans:r,error:i.message,durationMs:Date.now()-n}}finally{await t.end();}}async cleanAllOrphans(e={}){let{concurrency:n=10,onProgress:a,onError:r}=e,t=await this.config.tenantDiscovery(),i=[],s=false;for(let o=0;o<t.length&&!s;o+=n){let l=t.slice(o,o+n),c=await Promise.all(l.map(async u=>{if(s)return this.createSkippedSyncResult(u);try{a?.(u,"starting");let g=await this.cleanOrphans(u);return a?.(u,g.success?"completed":"failed"),g}catch(g){return a?.(u,"failed"),r?.(u,g)==="abort"&&(s=true),this.createErrorSyncResult(u,g)}}));i.push(...c);}return this.aggregateSyncResults(i)}async getAppliedMigrations(e,n,a){let r=a.columns.identifier,t=a.columns.timestamp;return (await e.query(`SELECT id, "${r}" as identifier, "${t}" as applied_at
|
|
63
|
+
FROM "${n}"."${a.tableName}"
|
|
64
|
+
ORDER BY id`)).rows.map(s=>{let o=a.columns.timestampType==="bigint"?new Date(Number(s.applied_at)):new Date(s.applied_at);return {identifier:s.identifier,appliedAt:o}})}isMigrationApplied(e,n,a){return a.columns.identifier==="name"?n.has(e.name):n.has(e.hash)||n.has(e.name)}async recordMigration(e,n,a,r){let{identifier:t,timestamp:i,timestampType:s}=r.columns,o=t==="name"?a.name:a.hash,l=s==="bigint"?Date.now():new Date;await e.query(`INSERT INTO "${n}"."${r.tableName}" ("${t}", "${i}") VALUES ($1, $2)`,[o,l]);}createSkippedSyncResult(e){return {tenantId:e,schemaName:this.deps.schemaNameTemplate(e),success:false,markedMigrations:[],removedOrphans:[],error:"Skipped due to abort",durationMs:0}}createErrorSyncResult(e,n){return {tenantId:e,schemaName:this.deps.schemaNameTemplate(e),success:false,markedMigrations:[],removedOrphans:[],error:n.message,durationMs:0}}aggregateSyncResults(e){return {total:e.length,succeeded:e.filter(n=>n.success).length,failed:e.filter(n=>!n.success).length,details:e}}};function ue(m,e){return new x(m,e)}var T=class{constructor(e,n){this.config=e;this.deps=n;}async migrateTenant(e,n,a={}){let r=Date.now(),t=this.deps.schemaNameTemplate(e),i=[],s=await this.deps.createPool(t);try{await this.config.hooks?.beforeTenant?.(e);let o=await this.deps.getOrDetectFormat(s,t);await this.deps.ensureMigrationsTable(s,t,o);let l=n??await this.deps.loadMigrations(),c=await this.getAppliedMigrations(s,t,o),u=new Set(c.map(h=>h.identifier)),g=l.filter(h=>!this.isMigrationApplied(h,u,o));if(a.dryRun)return {tenantId:e,schemaName:t,success:!0,appliedMigrations:g.map(h=>h.name),durationMs:Date.now()-r,format:o.format};for(let h of g){let y=Date.now();a.onProgress?.(e,"migrating",h.name),await this.config.hooks?.beforeMigration?.(e,h.name),await this.applyMigration(s,t,h,o),await this.config.hooks?.afterMigration?.(e,h.name,Date.now()-y),i.push(h.name);}let p={tenantId:e,schemaName:t,success:!0,appliedMigrations:i,durationMs:Date.now()-r,format:o.format};return await this.config.hooks?.afterTenant?.(e,p),p}catch(o){let l={tenantId:e,schemaName:t,success:false,appliedMigrations:i,error:o.message,durationMs:Date.now()-r};return await this.config.hooks?.afterTenant?.(e,l),l}finally{await s.end();}}async markAsApplied(e,n={}){let a=Date.now(),r=this.deps.schemaNameTemplate(e),t=[],i=await this.deps.createPool(r);try{await this.config.hooks?.beforeTenant?.(e);let s=await this.deps.getOrDetectFormat(i,r);await this.deps.ensureMigrationsTable(i,r,s);let o=await this.deps.loadMigrations(),l=await this.getAppliedMigrations(i,r,s),c=new Set(l.map(p=>p.identifier)),u=o.filter(p=>!this.isMigrationApplied(p,c,s));for(let p of u){let h=Date.now();n.onProgress?.(e,"migrating",p.name),await this.config.hooks?.beforeMigration?.(e,p.name),await this.recordMigration(i,r,p,s),await this.config.hooks?.afterMigration?.(e,p.name,Date.now()-h),t.push(p.name);}let g={tenantId:e,schemaName:r,success:!0,appliedMigrations:t,durationMs:Date.now()-a,format:s.format};return await this.config.hooks?.afterTenant?.(e,g),g}catch(s){let o={tenantId:e,schemaName:r,success:false,appliedMigrations:t,error:s.message,durationMs:Date.now()-a};return await this.config.hooks?.afterTenant?.(e,o),o}finally{await i.end();}}async getTenantStatus(e,n){let a=this.deps.schemaNameTemplate(e),r=await this.deps.createPool(a);try{let t=n??await this.deps.loadMigrations();if(!await this.deps.migrationsTableExists(r,a))return {tenantId:e,schemaName:a,appliedCount:0,pendingCount:t.length,pendingMigrations:t.map(u=>u.name),status:t.length>0?"behind":"ok",format:null};let s=await this.deps.getOrDetectFormat(r,a),o=await this.getAppliedMigrations(r,a,s),l=new Set(o.map(u=>u.identifier)),c=t.filter(u=>!this.isMigrationApplied(u,l,s));return {tenantId:e,schemaName:a,appliedCount:o.length,pendingCount:c.length,pendingMigrations:c.map(u=>u.name),status:c.length>0?"behind":"ok",format:s.format}}catch(t){return {tenantId:e,schemaName:a,appliedCount:0,pendingCount:0,pendingMigrations:[],status:"error",error:t.message,format:null}}finally{await r.end();}}async executeMigration(e,n,a,r,t){t?.markOnly?(t.onProgress?.("recording"),await this.recordMigration(e,n,a,r)):(t?.onProgress?.("applying"),await this.applyMigration(e,n,a,r));}async executeMigrations(e,n,a,r,t){let i=[];for(let s of a)await this.executeMigration(e,n,s,r,t),i.push(s.name);return i}async recordMigration(e,n,a,r){let{identifier:t,timestamp:i,timestampType:s}=r.columns,o=t==="name"?a.name:a.hash,l=s==="bigint"?Date.now():new Date;await e.query(`INSERT INTO "${n}"."${r.tableName}" ("${t}", "${i}") VALUES ($1, $2)`,[o,l]);}async getAppliedMigrations(e,n,a){let r=a.columns.identifier,t=a.columns.timestamp;return (await e.query(`SELECT id, "${r}" as identifier, "${t}" as applied_at
|
|
65
|
+
FROM "${n}"."${a.tableName}"
|
|
66
|
+
ORDER BY id`)).rows.map(s=>{let o=a.columns.timestampType==="bigint"?new Date(Number(s.applied_at)):new Date(s.applied_at);return {identifier:s.identifier,...a.columns.identifier==="name"?{name:s.identifier}:{hash:s.identifier},appliedAt:o}})}async getPendingMigrations(e,n,a,r){let t=await this.getAppliedMigrations(e,n,r),i=new Set(t.map(s=>s.identifier));return a.filter(s=>!this.isMigrationApplied(s,i,r))}isMigrationApplied(e,n,a){return a.columns.identifier==="name"?n.has(e.name):n.has(e.hash)||n.has(e.name)}async applyMigration(e,n,a,r){let t=await e.connect();try{await t.query("BEGIN"),await t.query(a.sql);let{identifier:i,timestamp:s,timestampType:o}=r.columns,l=i==="name"?a.name:a.hash,c=o==="bigint"?Date.now():new Date;await t.query(`INSERT INTO "${n}"."${r.tableName}" ("${i}", "${s}") VALUES ($1, $2)`,[l,c]),await t.query("COMMIT");}catch(i){throw await t.query("ROLLBACK"),i}finally{t.release();}}};function U(m,e){return new T(m,e)}var M=class{constructor(e,n,a){this.config=e;this.executor=n;this.loadMigrations=a;}async migrateAll(e={}){let{concurrency:n=10,onProgress:a,onError:r,dryRun:t=false}=e,i=await this.config.tenantDiscovery(),s=await this.loadMigrations(),o=[],l=false;for(let c=0;c<i.length&&!l;c+=n){let u=i.slice(c,c+n),g=await Promise.all(u.map(async p=>{if(l)return this.createSkippedResult(p);try{a?.(p,"starting");let h=await this.executor.migrateTenant(p,s,{dryRun:t,onProgress:a});return a?.(p,h.success?"completed":"failed"),h}catch(h){return a?.(p,"failed"),r?.(p,h)==="abort"&&(l=true),this.createErrorResult(p,h)}}));o.push(...g);}if(l){let c=i.slice(o.length);for(let u of c)o.push(this.createSkippedResult(u));}return this.aggregateResults(o)}async migrateTenants(e,n={}){let a=await this.loadMigrations(),r=[],{concurrency:t=10,onProgress:i,onError:s,dryRun:o=false}=n;for(let l=0;l<e.length;l+=t){let c=e.slice(l,l+t),u=await Promise.all(c.map(async g=>{try{i?.(g,"starting");let p=await this.executor.migrateTenant(g,a,{dryRun:o,onProgress:i});return i?.(g,p.success?"completed":"failed"),p}catch(p){return i?.(g,"failed"),s?.(g,p),this.createErrorResult(g,p)}}));r.push(...u);}return this.aggregateResults(r)}async markAllAsApplied(e={}){let{concurrency:n=10,onProgress:a,onError:r}=e,t=await this.config.tenantDiscovery(),i=[],s=false;for(let o=0;o<t.length&&!s;o+=n){let l=t.slice(o,o+n),c=await Promise.all(l.map(async u=>{if(s)return this.createSkippedResult(u);try{a?.(u,"starting");let g=await this.executor.markAsApplied(u,{onProgress:a});return a?.(u,g.success?"completed":"failed"),g}catch(g){return a?.(u,"failed"),r?.(u,g)==="abort"&&(s=true),this.createErrorResult(u,g)}}));i.push(...c);}if(s){let o=t.slice(i.length);for(let l of o)i.push(this.createSkippedResult(l));}return this.aggregateResults(i)}async getStatus(){let e=await this.config.tenantDiscovery(),n=await this.loadMigrations(),a=[];for(let r of e)a.push(await this.executor.getTenantStatus(r,n));return a}createSkippedResult(e){return {tenantId:e,schemaName:"",success:false,appliedMigrations:[],error:"Skipped due to abort",durationMs:0}}createErrorResult(e,n){return {tenantId:e,schemaName:"",success:false,appliedMigrations:[],error:n.message,durationMs:0}}aggregateResults(e){return {total:e.length,succeeded:e.filter(n=>n.success).length,failed:e.filter(n=>!n.success&&n.error!=="Skipped due to abort").length,skipped:e.filter(n=>n.error==="Skipped due to abort").length,details:e}}};function H(m,e,n){return new M(m,e,n)}async function Y(m,e,n=[]){let a=n.length>0?n.map((t,i)=>`$${i+2}`).join(", "):"''::text";return (await m.query(`SELECT table_name
|
|
2236
67
|
FROM information_schema.tables
|
|
2237
68
|
WHERE table_schema = $1
|
|
2238
69
|
AND table_type = 'BASE TABLE'
|
|
2239
|
-
AND table_name NOT IN (${
|
|
2240
|
-
ORDER BY table_name`,
|
|
2241
|
-
[schemaName, ...excludeTables]
|
|
2242
|
-
);
|
|
2243
|
-
return result.rows.map((r) => r.table_name);
|
|
2244
|
-
}
|
|
2245
|
-
async function getColumns(pool, schemaName, tableName) {
|
|
2246
|
-
const result = await pool.query(
|
|
2247
|
-
`SELECT
|
|
70
|
+
AND table_name NOT IN (${a})
|
|
71
|
+
ORDER BY table_name`,[e,...n])).rows.map(t=>t.table_name)}async function ge(m,e,n){return (await m.query(`SELECT
|
|
2248
72
|
column_name,
|
|
2249
73
|
data_type,
|
|
2250
74
|
udt_name,
|
|
@@ -2255,68 +79,13 @@ async function getColumns(pool, schemaName, tableName) {
|
|
|
2255
79
|
numeric_scale
|
|
2256
80
|
FROM information_schema.columns
|
|
2257
81
|
WHERE table_schema = $1 AND table_name = $2
|
|
2258
|
-
ORDER BY ordinal_position`,
|
|
2259
|
-
|
|
2260
|
-
)
|
|
2261
|
-
|
|
2262
|
-
columnName: row.column_name,
|
|
2263
|
-
dataType: row.data_type,
|
|
2264
|
-
udtName: row.udt_name,
|
|
2265
|
-
isNullable: row.is_nullable === "YES",
|
|
2266
|
-
columnDefault: row.column_default,
|
|
2267
|
-
characterMaximumLength: row.character_maximum_length,
|
|
2268
|
-
numericPrecision: row.numeric_precision,
|
|
2269
|
-
numericScale: row.numeric_scale
|
|
2270
|
-
}));
|
|
2271
|
-
}
|
|
2272
|
-
async function generateTableDdl(pool, schemaName, tableName) {
|
|
2273
|
-
const columns = await getColumns(pool, schemaName, tableName);
|
|
2274
|
-
const columnDefs = columns.map((col) => {
|
|
2275
|
-
let type = col.udtName;
|
|
2276
|
-
if (col.dataType === "character varying" && col.characterMaximumLength) {
|
|
2277
|
-
type = `varchar(${col.characterMaximumLength})`;
|
|
2278
|
-
} else if (col.dataType === "character" && col.characterMaximumLength) {
|
|
2279
|
-
type = `char(${col.characterMaximumLength})`;
|
|
2280
|
-
} else if (col.dataType === "numeric" && col.numericPrecision) {
|
|
2281
|
-
type = `numeric(${col.numericPrecision}${col.numericScale ? `, ${col.numericScale}` : ""})`;
|
|
2282
|
-
} else if (col.dataType === "ARRAY") {
|
|
2283
|
-
type = col.udtName.replace(/^_/, "") + "[]";
|
|
2284
|
-
}
|
|
2285
|
-
let definition = `"${col.columnName}" ${type}`;
|
|
2286
|
-
if (!col.isNullable) {
|
|
2287
|
-
definition += " NOT NULL";
|
|
2288
|
-
}
|
|
2289
|
-
if (col.columnDefault) {
|
|
2290
|
-
const defaultValue = col.columnDefault.replace(
|
|
2291
|
-
new RegExp(`"?${schemaName}"?\\.`, "g"),
|
|
2292
|
-
""
|
|
2293
|
-
);
|
|
2294
|
-
definition += ` DEFAULT ${defaultValue}`;
|
|
2295
|
-
}
|
|
2296
|
-
return definition;
|
|
2297
|
-
});
|
|
2298
|
-
return `CREATE TABLE IF NOT EXISTS "${tableName}" (
|
|
2299
|
-
${columnDefs.join(",\n ")}
|
|
2300
|
-
)`;
|
|
2301
|
-
}
|
|
2302
|
-
async function generateIndexDdls(pool, sourceSchema, targetSchema, tableName) {
|
|
2303
|
-
const result = await pool.query(
|
|
2304
|
-
`SELECT indexname, indexdef
|
|
82
|
+
ORDER BY ordinal_position`,[e,n])).rows.map(r=>({columnName:r.column_name,dataType:r.data_type,udtName:r.udt_name,isNullable:r.is_nullable==="YES",columnDefault:r.column_default,characterMaximumLength:r.character_maximum_length,numericPrecision:r.numeric_precision,numericScale:r.numeric_scale}))}async function pe(m,e,n){let r=(await ge(m,e,n)).map(t=>{let i=t.udtName;t.dataType==="character varying"&&t.characterMaximumLength?i=`varchar(${t.characterMaximumLength})`:t.dataType==="character"&&t.characterMaximumLength?i=`char(${t.characterMaximumLength})`:t.dataType==="numeric"&&t.numericPrecision?i=`numeric(${t.numericPrecision}${t.numericScale?`, ${t.numericScale}`:""})`:t.dataType==="ARRAY"&&(i=t.udtName.replace(/^_/,"")+"[]");let s=`"${t.columnName}" ${i}`;if(t.isNullable||(s+=" NOT NULL"),t.columnDefault){let o=t.columnDefault.replace(new RegExp(`"?${e}"?\\.`,"g"),"");s+=` DEFAULT ${o}`;}return s});return `CREATE TABLE IF NOT EXISTS "${n}" (
|
|
83
|
+
${r.join(`,
|
|
84
|
+
`)}
|
|
85
|
+
)`}async function he(m,e,n,a){return (await m.query(`SELECT indexname, indexdef
|
|
2305
86
|
FROM pg_indexes
|
|
2306
87
|
WHERE schemaname = $1 AND tablename = $2
|
|
2307
|
-
AND indexname NOT LIKE '%_pkey'`,
|
|
2308
|
-
[sourceSchema, tableName]
|
|
2309
|
-
);
|
|
2310
|
-
return result.rows.map(
|
|
2311
|
-
(row) => (
|
|
2312
|
-
// Replace source schema with target schema
|
|
2313
|
-
row.indexdef.replace(new RegExp(`ON "${sourceSchema}"\\."`, "g"), `ON "${targetSchema}"."`).replace(new RegExp(`"${sourceSchema}"\\."`, "g"), `"${targetSchema}"."`)
|
|
2314
|
-
)
|
|
2315
|
-
);
|
|
2316
|
-
}
|
|
2317
|
-
async function generatePrimaryKeyDdl(pool, schemaName, tableName) {
|
|
2318
|
-
const result = await pool.query(
|
|
2319
|
-
`SELECT
|
|
88
|
+
AND indexname NOT LIKE '%_pkey'`,[e,a])).rows.map(t=>t.indexdef.replace(new RegExp(`ON "${e}"\\."`,"g"),`ON "${n}"."`).replace(new RegExp(`"${e}"\\."`,"g"),`"${n}"."`))}async function de(m,e,n){let a=await m.query(`SELECT
|
|
2320
89
|
tc.constraint_name,
|
|
2321
90
|
kcu.column_name
|
|
2322
91
|
FROM information_schema.table_constraints tc
|
|
@@ -2326,17 +95,7 @@ async function generatePrimaryKeyDdl(pool, schemaName, tableName) {
|
|
|
2326
95
|
WHERE tc.table_schema = $1
|
|
2327
96
|
AND tc.table_name = $2
|
|
2328
97
|
AND tc.constraint_type = 'PRIMARY KEY'
|
|
2329
|
-
ORDER BY kcu.ordinal_position`,
|
|
2330
|
-
[schemaName, tableName]
|
|
2331
|
-
);
|
|
2332
|
-
if (result.rows.length === 0) return null;
|
|
2333
|
-
const columns = result.rows.map((r) => `"${r.column_name}"`).join(", ");
|
|
2334
|
-
const constraintName = result.rows[0].constraint_name;
|
|
2335
|
-
return `ALTER TABLE "${tableName}" ADD CONSTRAINT "${constraintName}" PRIMARY KEY (${columns})`;
|
|
2336
|
-
}
|
|
2337
|
-
async function generateForeignKeyDdls(pool, sourceSchema, targetSchema, tableName) {
|
|
2338
|
-
const result = await pool.query(
|
|
2339
|
-
`SELECT
|
|
98
|
+
ORDER BY kcu.ordinal_position`,[e,n]);if(a.rows.length===0)return null;let r=a.rows.map(i=>`"${i.column_name}"`).join(", "),t=a.rows[0].constraint_name;return `ALTER TABLE "${n}" ADD CONSTRAINT "${t}" PRIMARY KEY (${r})`}async function fe(m,e,n,a){let r=await m.query(`SELECT
|
|
2340
99
|
tc.constraint_name,
|
|
2341
100
|
kcu.column_name,
|
|
2342
101
|
ccu.table_name as foreign_table_name,
|
|
@@ -2356,43 +115,7 @@ async function generateForeignKeyDdls(pool, sourceSchema, targetSchema, tableNam
|
|
|
2356
115
|
WHERE tc.table_schema = $1
|
|
2357
116
|
AND tc.table_name = $2
|
|
2358
117
|
AND tc.constraint_type = 'FOREIGN KEY'
|
|
2359
|
-
ORDER BY tc.constraint_name, kcu.ordinal_position`,
|
|
2360
|
-
[sourceSchema, tableName]
|
|
2361
|
-
);
|
|
2362
|
-
const fkMap = /* @__PURE__ */ new Map();
|
|
2363
|
-
for (const row of result.rows) {
|
|
2364
|
-
const existing = fkMap.get(row.constraint_name);
|
|
2365
|
-
if (existing) {
|
|
2366
|
-
existing.columns.push(row.column_name);
|
|
2367
|
-
existing.foreignColumns.push(row.foreign_column_name);
|
|
2368
|
-
} else {
|
|
2369
|
-
fkMap.set(row.constraint_name, {
|
|
2370
|
-
columns: [row.column_name],
|
|
2371
|
-
foreignTable: row.foreign_table_name,
|
|
2372
|
-
foreignColumns: [row.foreign_column_name],
|
|
2373
|
-
updateRule: row.update_rule,
|
|
2374
|
-
deleteRule: row.delete_rule
|
|
2375
|
-
});
|
|
2376
|
-
}
|
|
2377
|
-
}
|
|
2378
|
-
return Array.from(fkMap.entries()).map(([name, fk]) => {
|
|
2379
|
-
const columns = fk.columns.map((c) => `"${c}"`).join(", ");
|
|
2380
|
-
const foreignColumns = fk.foreignColumns.map((c) => `"${c}"`).join(", ");
|
|
2381
|
-
let ddl = `ALTER TABLE "${targetSchema}"."${tableName}" `;
|
|
2382
|
-
ddl += `ADD CONSTRAINT "${name}" FOREIGN KEY (${columns}) `;
|
|
2383
|
-
ddl += `REFERENCES "${targetSchema}"."${fk.foreignTable}" (${foreignColumns})`;
|
|
2384
|
-
if (fk.updateRule !== "NO ACTION") {
|
|
2385
|
-
ddl += ` ON UPDATE ${fk.updateRule}`;
|
|
2386
|
-
}
|
|
2387
|
-
if (fk.deleteRule !== "NO ACTION") {
|
|
2388
|
-
ddl += ` ON DELETE ${fk.deleteRule}`;
|
|
2389
|
-
}
|
|
2390
|
-
return ddl;
|
|
2391
|
-
});
|
|
2392
|
-
}
|
|
2393
|
-
async function generateUniqueDdls(pool, schemaName, tableName) {
|
|
2394
|
-
const result = await pool.query(
|
|
2395
|
-
`SELECT
|
|
118
|
+
ORDER BY tc.constraint_name, kcu.ordinal_position`,[e,a]),t=new Map;for(let i of r.rows){let s=t.get(i.constraint_name);s?(s.columns.push(i.column_name),s.foreignColumns.push(i.foreign_column_name)):t.set(i.constraint_name,{columns:[i.column_name],foreignTable:i.foreign_table_name,foreignColumns:[i.foreign_column_name],updateRule:i.update_rule,deleteRule:i.delete_rule});}return Array.from(t.entries()).map(([i,s])=>{let o=s.columns.map(u=>`"${u}"`).join(", "),l=s.foreignColumns.map(u=>`"${u}"`).join(", "),c=`ALTER TABLE "${n}"."${a}" `;return c+=`ADD CONSTRAINT "${i}" FOREIGN KEY (${o}) `,c+=`REFERENCES "${n}"."${s.foreignTable}" (${l})`,s.updateRule!=="NO ACTION"&&(c+=` ON UPDATE ${s.updateRule}`),s.deleteRule!=="NO ACTION"&&(c+=` ON DELETE ${s.deleteRule}`),c})}async function Se(m,e,n){let a=await m.query(`SELECT
|
|
2396
119
|
tc.constraint_name,
|
|
2397
120
|
kcu.column_name
|
|
2398
121
|
FROM information_schema.table_constraints tc
|
|
@@ -2402,26 +125,7 @@ async function generateUniqueDdls(pool, schemaName, tableName) {
|
|
|
2402
125
|
WHERE tc.table_schema = $1
|
|
2403
126
|
AND tc.table_name = $2
|
|
2404
127
|
AND tc.constraint_type = 'UNIQUE'
|
|
2405
|
-
ORDER BY tc.constraint_name, kcu.ordinal_position`,
|
|
2406
|
-
[schemaName, tableName]
|
|
2407
|
-
);
|
|
2408
|
-
const uniqueMap = /* @__PURE__ */ new Map();
|
|
2409
|
-
for (const row of result.rows) {
|
|
2410
|
-
const existing = uniqueMap.get(row.constraint_name);
|
|
2411
|
-
if (existing) {
|
|
2412
|
-
existing.push(row.column_name);
|
|
2413
|
-
} else {
|
|
2414
|
-
uniqueMap.set(row.constraint_name, [row.column_name]);
|
|
2415
|
-
}
|
|
2416
|
-
}
|
|
2417
|
-
return Array.from(uniqueMap.entries()).map(([name, columns]) => {
|
|
2418
|
-
const cols = columns.map((c) => `"${c}"`).join(", ");
|
|
2419
|
-
return `ALTER TABLE "${tableName}" ADD CONSTRAINT "${name}" UNIQUE (${cols})`;
|
|
2420
|
-
});
|
|
2421
|
-
}
|
|
2422
|
-
async function generateCheckDdls(pool, schemaName, tableName) {
|
|
2423
|
-
const result = await pool.query(
|
|
2424
|
-
`SELECT
|
|
128
|
+
ORDER BY tc.constraint_name, kcu.ordinal_position`,[e,n]),r=new Map;for(let t of a.rows){let i=r.get(t.constraint_name);i?i.push(t.column_name):r.set(t.constraint_name,[t.column_name]);}return Array.from(r.entries()).map(([t,i])=>{let s=i.map(o=>`"${o}"`).join(", ");return `ALTER TABLE "${n}" ADD CONSTRAINT "${t}" UNIQUE (${s})`})}async function ye(m,e,n){return (await m.query(`SELECT
|
|
2425
129
|
tc.constraint_name,
|
|
2426
130
|
cc.check_clause
|
|
2427
131
|
FROM information_schema.table_constraints tc
|
|
@@ -2431,91 +135,12 @@ async function generateCheckDdls(pool, schemaName, tableName) {
|
|
|
2431
135
|
WHERE tc.table_schema = $1
|
|
2432
136
|
AND tc.table_name = $2
|
|
2433
137
|
AND tc.constraint_type = 'CHECK'
|
|
2434
|
-
AND tc.constraint_name NOT LIKE '%_not_null'`,
|
|
2435
|
-
[schemaName, tableName]
|
|
2436
|
-
);
|
|
2437
|
-
return result.rows.map(
|
|
2438
|
-
(row) => `ALTER TABLE "${tableName}" ADD CONSTRAINT "${row.constraint_name}" CHECK (${row.check_clause})`
|
|
2439
|
-
);
|
|
2440
|
-
}
|
|
2441
|
-
async function getRowCount(pool, schemaName, tableName) {
|
|
2442
|
-
const result = await pool.query(
|
|
2443
|
-
`SELECT count(*) FROM "${schemaName}"."${tableName}"`
|
|
2444
|
-
);
|
|
2445
|
-
return parseInt(result.rows[0].count, 10);
|
|
2446
|
-
}
|
|
2447
|
-
async function generateTableCloneInfo(pool, sourceSchema, targetSchema, tableName) {
|
|
2448
|
-
const [createDdl, indexDdls, pkDdl, uniqueDdls, checkDdls, fkDdls, rowCount] = await Promise.all([
|
|
2449
|
-
generateTableDdl(pool, sourceSchema, tableName),
|
|
2450
|
-
generateIndexDdls(pool, sourceSchema, targetSchema, tableName),
|
|
2451
|
-
generatePrimaryKeyDdl(pool, sourceSchema, tableName),
|
|
2452
|
-
generateUniqueDdls(pool, sourceSchema, tableName),
|
|
2453
|
-
generateCheckDdls(pool, sourceSchema, tableName),
|
|
2454
|
-
generateForeignKeyDdls(pool, sourceSchema, targetSchema, tableName),
|
|
2455
|
-
getRowCount(pool, sourceSchema, tableName)
|
|
2456
|
-
]);
|
|
2457
|
-
return {
|
|
2458
|
-
name: tableName,
|
|
2459
|
-
createDdl,
|
|
2460
|
-
indexDdls,
|
|
2461
|
-
constraintDdls: [
|
|
2462
|
-
...pkDdl ? [pkDdl] : [],
|
|
2463
|
-
...uniqueDdls,
|
|
2464
|
-
...checkDdls,
|
|
2465
|
-
...fkDdls
|
|
2466
|
-
],
|
|
2467
|
-
rowCount
|
|
2468
|
-
};
|
|
2469
|
-
}
|
|
2470
|
-
|
|
2471
|
-
// src/migrator/clone/data-copier.ts
|
|
2472
|
-
async function getTableColumns(pool, schemaName, tableName) {
|
|
2473
|
-
const result = await pool.query(
|
|
2474
|
-
`SELECT column_name
|
|
138
|
+
AND tc.constraint_name NOT LIKE '%_not_null'`,[e,n])).rows.map(r=>`ALTER TABLE "${n}" ADD CONSTRAINT "${r.constraint_name}" CHECK (${r.check_clause})`)}async function Te(m,e,n){let a=await m.query(`SELECT count(*) FROM "${e}"."${n}"`);return parseInt(a.rows[0].count,10)}async function W(m,e,n,a){let[r,t,i,s,o,l,c]=await Promise.all([pe(m,e,a),he(m,e,n,a),de(m,e,a),Se(m,e,a),ye(m,e,a),fe(m,e,n,a),Te(m,e,a)]);return {name:a,createDdl:r,indexDdls:t,constraintDdls:[...i?[i]:[],...s,...o,...l],rowCount:c}}async function Me(m,e,n){return (await m.query(`SELECT column_name
|
|
2475
139
|
FROM information_schema.columns
|
|
2476
140
|
WHERE table_schema = $1 AND table_name = $2
|
|
2477
|
-
ORDER BY ordinal_position`,
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
return result.rows.map((r) => r.column_name);
|
|
2481
|
-
}
|
|
2482
|
-
function formatAnonymizeValue(value) {
|
|
2483
|
-
if (value === null) {
|
|
2484
|
-
return "NULL";
|
|
2485
|
-
}
|
|
2486
|
-
if (typeof value === "string") {
|
|
2487
|
-
return `'${value.replace(/'/g, "''")}'`;
|
|
2488
|
-
}
|
|
2489
|
-
if (typeof value === "boolean") {
|
|
2490
|
-
return value ? "TRUE" : "FALSE";
|
|
2491
|
-
}
|
|
2492
|
-
return String(value);
|
|
2493
|
-
}
|
|
2494
|
-
async function copyTableData(pool, sourceSchema, targetSchema, tableName, anonymizeRules) {
|
|
2495
|
-
const columns = await getTableColumns(pool, sourceSchema, tableName);
|
|
2496
|
-
if (columns.length === 0) {
|
|
2497
|
-
return 0;
|
|
2498
|
-
}
|
|
2499
|
-
const tableRules = anonymizeRules?.[tableName] ?? {};
|
|
2500
|
-
const selectColumns = columns.map((col) => {
|
|
2501
|
-
if (col in tableRules) {
|
|
2502
|
-
const value = tableRules[col];
|
|
2503
|
-
return `${formatAnonymizeValue(value)} as "${col}"`;
|
|
2504
|
-
}
|
|
2505
|
-
return `"${col}"`;
|
|
2506
|
-
});
|
|
2507
|
-
const insertColumns = columns.map((c) => `"${c}"`).join(", ");
|
|
2508
|
-
const selectExpr = selectColumns.join(", ");
|
|
2509
|
-
const result = await pool.query(
|
|
2510
|
-
`INSERT INTO "${targetSchema}"."${tableName}" (${insertColumns})
|
|
2511
|
-
SELECT ${selectExpr}
|
|
2512
|
-
FROM "${sourceSchema}"."${tableName}"`
|
|
2513
|
-
);
|
|
2514
|
-
return result.rowCount ?? 0;
|
|
2515
|
-
}
|
|
2516
|
-
async function getTablesInDependencyOrder(pool, schemaName, tables) {
|
|
2517
|
-
const result = await pool.query(
|
|
2518
|
-
`SELECT DISTINCT
|
|
141
|
+
ORDER BY ordinal_position`,[e,n])).rows.map(r=>r.column_name)}function _e(m){return m===null?"NULL":typeof m=="string"?`'${m.replace(/'/g,"''")}'`:typeof m=="boolean"?m?"TRUE":"FALSE":String(m)}async function Ee(m,e,n,a,r){let t=await Me(m,e,a);if(t.length===0)return 0;let i=r?.[a]??{},s=t.map(u=>{if(u in i){let g=i[u];return `${_e(g)} as "${u}"`}return `"${u}"`}),o=t.map(u=>`"${u}"`).join(", "),l=s.join(", ");return (await m.query(`INSERT INTO "${n}"."${a}" (${o})
|
|
142
|
+
SELECT ${l}
|
|
143
|
+
FROM "${e}"."${a}"`)).rowCount??0}async function be(m,e,n){let a=await m.query(`SELECT DISTINCT
|
|
2519
144
|
tc.table_name,
|
|
2520
145
|
ccu.table_name as foreign_table_name
|
|
2521
146
|
FROM information_schema.table_constraints tc
|
|
@@ -2524,587 +149,6 @@ async function getTablesInDependencyOrder(pool, schemaName, tables) {
|
|
|
2524
149
|
AND tc.table_schema = ccu.table_schema
|
|
2525
150
|
WHERE tc.table_schema = $1
|
|
2526
151
|
AND tc.constraint_type = 'FOREIGN KEY'
|
|
2527
|
-
AND tc.table_name != ccu.table_name`,
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
const dependencies = /* @__PURE__ */ new Map();
|
|
2531
|
-
const tableSet = new Set(tables);
|
|
2532
|
-
for (const table of tables) {
|
|
2533
|
-
dependencies.set(table, /* @__PURE__ */ new Set());
|
|
2534
|
-
}
|
|
2535
|
-
for (const row of result.rows) {
|
|
2536
|
-
if (tableSet.has(row.table_name) && tableSet.has(row.foreign_table_name)) {
|
|
2537
|
-
dependencies.get(row.table_name).add(row.foreign_table_name);
|
|
2538
|
-
}
|
|
2539
|
-
}
|
|
2540
|
-
const sorted = [];
|
|
2541
|
-
const inDegree = /* @__PURE__ */ new Map();
|
|
2542
|
-
const queue = [];
|
|
2543
|
-
for (const table of tables) {
|
|
2544
|
-
inDegree.set(table, 0);
|
|
2545
|
-
}
|
|
2546
|
-
for (const [table, deps] of dependencies) {
|
|
2547
|
-
for (const dep of deps) {
|
|
2548
|
-
inDegree.set(dep, (inDegree.get(dep) ?? 0) + 1);
|
|
2549
|
-
}
|
|
2550
|
-
}
|
|
2551
|
-
for (const [table, degree] of inDegree) {
|
|
2552
|
-
if (degree === 0) {
|
|
2553
|
-
queue.push(table);
|
|
2554
|
-
}
|
|
2555
|
-
}
|
|
2556
|
-
while (queue.length > 0) {
|
|
2557
|
-
const table = queue.shift();
|
|
2558
|
-
sorted.push(table);
|
|
2559
|
-
for (const [otherTable, deps] of dependencies) {
|
|
2560
|
-
if (deps.has(table)) {
|
|
2561
|
-
deps.delete(table);
|
|
2562
|
-
const newDegree = (inDegree.get(otherTable) ?? 0) - 1;
|
|
2563
|
-
inDegree.set(otherTable, newDegree);
|
|
2564
|
-
if (newDegree === 0) {
|
|
2565
|
-
queue.push(otherTable);
|
|
2566
|
-
}
|
|
2567
|
-
}
|
|
2568
|
-
}
|
|
2569
|
-
}
|
|
2570
|
-
const remaining = tables.filter((t) => !sorted.includes(t));
|
|
2571
|
-
return [...sorted, ...remaining];
|
|
2572
|
-
}
|
|
2573
|
-
async function copyAllData(pool, sourceSchema, targetSchema, tables, anonymizeRules, onProgress) {
|
|
2574
|
-
let totalRows = 0;
|
|
2575
|
-
const orderedTables = await getTablesInDependencyOrder(pool, sourceSchema, tables);
|
|
2576
|
-
await pool.query("SET session_replication_role = replica");
|
|
2577
|
-
try {
|
|
2578
|
-
for (let i = 0; i < orderedTables.length; i++) {
|
|
2579
|
-
const table = orderedTables[i];
|
|
2580
|
-
onProgress?.("copying_data", {
|
|
2581
|
-
table,
|
|
2582
|
-
progress: i + 1,
|
|
2583
|
-
total: orderedTables.length
|
|
2584
|
-
});
|
|
2585
|
-
const rows = await copyTableData(pool, sourceSchema, targetSchema, table, anonymizeRules);
|
|
2586
|
-
totalRows += rows;
|
|
2587
|
-
}
|
|
2588
|
-
} finally {
|
|
2589
|
-
await pool.query("SET session_replication_role = DEFAULT");
|
|
2590
|
-
}
|
|
2591
|
-
return totalRows;
|
|
2592
|
-
}
|
|
2593
|
-
|
|
2594
|
-
// src/migrator/clone/cloner.ts
|
|
2595
|
-
var DEFAULT_MIGRATIONS_TABLE3 = "__drizzle_migrations";
|
|
2596
|
-
var Cloner = class {
|
|
2597
|
-
constructor(config, deps) {
|
|
2598
|
-
this.deps = deps;
|
|
2599
|
-
this.migrationsTable = config.migrationsTable ?? DEFAULT_MIGRATIONS_TABLE3;
|
|
2600
|
-
}
|
|
2601
|
-
migrationsTable;
|
|
2602
|
-
/**
|
|
2603
|
-
* Clone a tenant to another
|
|
2604
|
-
*
|
|
2605
|
-
* @param sourceTenantId - Source tenant ID
|
|
2606
|
-
* @param targetTenantId - Target tenant ID
|
|
2607
|
-
* @param options - Clone options
|
|
2608
|
-
* @returns Clone result
|
|
2609
|
-
*/
|
|
2610
|
-
async cloneTenant(sourceTenantId, targetTenantId, options = {}) {
|
|
2611
|
-
const startTime = Date.now();
|
|
2612
|
-
const {
|
|
2613
|
-
includeData = false,
|
|
2614
|
-
anonymize,
|
|
2615
|
-
excludeTables = [],
|
|
2616
|
-
onProgress
|
|
2617
|
-
} = options;
|
|
2618
|
-
const sourceSchema = this.deps.schemaNameTemplate(sourceTenantId);
|
|
2619
|
-
const targetSchema = this.deps.schemaNameTemplate(targetTenantId);
|
|
2620
|
-
const allExcludes = [this.migrationsTable, ...excludeTables];
|
|
2621
|
-
let sourcePool = null;
|
|
2622
|
-
let rootPool = null;
|
|
2623
|
-
try {
|
|
2624
|
-
onProgress?.("starting");
|
|
2625
|
-
const sourceExists = await this.deps.schemaExists(sourceTenantId);
|
|
2626
|
-
if (!sourceExists) {
|
|
2627
|
-
return this.createErrorResult(
|
|
2628
|
-
sourceTenantId,
|
|
2629
|
-
targetTenantId,
|
|
2630
|
-
targetSchema,
|
|
2631
|
-
`Source tenant "${sourceTenantId}" does not exist`,
|
|
2632
|
-
startTime
|
|
2633
|
-
);
|
|
2634
|
-
}
|
|
2635
|
-
const targetExists = await this.deps.schemaExists(targetTenantId);
|
|
2636
|
-
if (targetExists) {
|
|
2637
|
-
return this.createErrorResult(
|
|
2638
|
-
sourceTenantId,
|
|
2639
|
-
targetTenantId,
|
|
2640
|
-
targetSchema,
|
|
2641
|
-
`Target tenant "${targetTenantId}" already exists`,
|
|
2642
|
-
startTime
|
|
2643
|
-
);
|
|
2644
|
-
}
|
|
2645
|
-
onProgress?.("introspecting");
|
|
2646
|
-
sourcePool = await this.deps.createPool(sourceSchema);
|
|
2647
|
-
const tables = await listTables(sourcePool, sourceSchema, allExcludes);
|
|
2648
|
-
if (tables.length === 0) {
|
|
2649
|
-
onProgress?.("creating_schema");
|
|
2650
|
-
await this.deps.createSchema(targetTenantId);
|
|
2651
|
-
onProgress?.("completed");
|
|
2652
|
-
return {
|
|
2653
|
-
sourceTenant: sourceTenantId,
|
|
2654
|
-
targetTenant: targetTenantId,
|
|
2655
|
-
targetSchema,
|
|
2656
|
-
success: true,
|
|
2657
|
-
tables: [],
|
|
2658
|
-
durationMs: Date.now() - startTime
|
|
2659
|
-
};
|
|
2660
|
-
}
|
|
2661
|
-
const tableInfos = await Promise.all(
|
|
2662
|
-
tables.map((t) => generateTableCloneInfo(sourcePool, sourceSchema, targetSchema, t))
|
|
2663
|
-
);
|
|
2664
|
-
await sourcePool.end();
|
|
2665
|
-
sourcePool = null;
|
|
2666
|
-
onProgress?.("creating_schema");
|
|
2667
|
-
await this.deps.createSchema(targetTenantId);
|
|
2668
|
-
rootPool = await this.deps.createRootPool();
|
|
2669
|
-
onProgress?.("creating_tables");
|
|
2670
|
-
for (const info of tableInfos) {
|
|
2671
|
-
await rootPool.query(`SET search_path TO "${targetSchema}"; ${info.createDdl}`);
|
|
2672
|
-
}
|
|
2673
|
-
onProgress?.("creating_constraints");
|
|
2674
|
-
for (const info of tableInfos) {
|
|
2675
|
-
for (const constraint of info.constraintDdls.filter((c) => !c.includes("FOREIGN KEY"))) {
|
|
2676
|
-
try {
|
|
2677
|
-
await rootPool.query(`SET search_path TO "${targetSchema}"; ${constraint}`);
|
|
2678
|
-
} catch (error) {
|
|
2679
|
-
}
|
|
2680
|
-
}
|
|
2681
|
-
}
|
|
2682
|
-
onProgress?.("creating_indexes");
|
|
2683
|
-
for (const info of tableInfos) {
|
|
2684
|
-
for (const index of info.indexDdls) {
|
|
2685
|
-
try {
|
|
2686
|
-
await rootPool.query(index);
|
|
2687
|
-
} catch (error) {
|
|
2688
|
-
}
|
|
2689
|
-
}
|
|
2690
|
-
}
|
|
2691
|
-
let rowsCopied = 0;
|
|
2692
|
-
if (includeData) {
|
|
2693
|
-
onProgress?.("copying_data");
|
|
2694
|
-
rowsCopied = await copyAllData(
|
|
2695
|
-
rootPool,
|
|
2696
|
-
sourceSchema,
|
|
2697
|
-
targetSchema,
|
|
2698
|
-
tables,
|
|
2699
|
-
anonymize?.enabled ? anonymize.rules : void 0,
|
|
2700
|
-
onProgress
|
|
2701
|
-
);
|
|
2702
|
-
}
|
|
2703
|
-
for (const info of tableInfos) {
|
|
2704
|
-
for (const fk of info.constraintDdls.filter((c) => c.includes("FOREIGN KEY"))) {
|
|
2705
|
-
try {
|
|
2706
|
-
await rootPool.query(fk);
|
|
2707
|
-
} catch (error) {
|
|
2708
|
-
}
|
|
2709
|
-
}
|
|
2710
|
-
}
|
|
2711
|
-
onProgress?.("completed");
|
|
2712
|
-
const result = {
|
|
2713
|
-
sourceTenant: sourceTenantId,
|
|
2714
|
-
targetTenant: targetTenantId,
|
|
2715
|
-
targetSchema,
|
|
2716
|
-
success: true,
|
|
2717
|
-
tables,
|
|
2718
|
-
durationMs: Date.now() - startTime
|
|
2719
|
-
};
|
|
2720
|
-
if (includeData) {
|
|
2721
|
-
result.rowsCopied = rowsCopied;
|
|
2722
|
-
}
|
|
2723
|
-
return result;
|
|
2724
|
-
} catch (error) {
|
|
2725
|
-
options.onError?.(error);
|
|
2726
|
-
onProgress?.("failed");
|
|
2727
|
-
return this.createErrorResult(
|
|
2728
|
-
sourceTenantId,
|
|
2729
|
-
targetTenantId,
|
|
2730
|
-
targetSchema,
|
|
2731
|
-
error.message,
|
|
2732
|
-
startTime
|
|
2733
|
-
);
|
|
2734
|
-
} finally {
|
|
2735
|
-
if (sourcePool) {
|
|
2736
|
-
await sourcePool.end().catch(() => {
|
|
2737
|
-
});
|
|
2738
|
-
}
|
|
2739
|
-
if (rootPool) {
|
|
2740
|
-
await rootPool.end().catch(() => {
|
|
2741
|
-
});
|
|
2742
|
-
}
|
|
2743
|
-
}
|
|
2744
|
-
}
|
|
2745
|
-
createErrorResult(source, target, schema, error, startTime) {
|
|
2746
|
-
return {
|
|
2747
|
-
sourceTenant: source,
|
|
2748
|
-
targetTenant: target,
|
|
2749
|
-
targetSchema: schema,
|
|
2750
|
-
success: false,
|
|
2751
|
-
error,
|
|
2752
|
-
tables: [],
|
|
2753
|
-
durationMs: Date.now() - startTime
|
|
2754
|
-
};
|
|
2755
|
-
}
|
|
2756
|
-
};
|
|
2757
|
-
function createCloner(config, dependencies) {
|
|
2758
|
-
return new Cloner(config, dependencies);
|
|
2759
|
-
}
|
|
2760
|
-
|
|
2761
|
-
// src/migrator/migrator.ts
|
|
2762
|
-
var DEFAULT_MIGRATIONS_TABLE4 = "__drizzle_migrations";
|
|
2763
|
-
var Migrator = class {
|
|
2764
|
-
constructor(tenantConfig, migratorConfig) {
|
|
2765
|
-
this.migratorConfig = migratorConfig;
|
|
2766
|
-
this.migrationsTable = migratorConfig.migrationsTable ?? DEFAULT_MIGRATIONS_TABLE4;
|
|
2767
|
-
this.schemaManager = new SchemaManager(tenantConfig, this.migrationsTable);
|
|
2768
|
-
this.driftDetector = new DriftDetector(tenantConfig, this.schemaManager, {
|
|
2769
|
-
migrationsTable: this.migrationsTable,
|
|
2770
|
-
tenantDiscovery: migratorConfig.tenantDiscovery
|
|
2771
|
-
});
|
|
2772
|
-
this.seeder = new Seeder(
|
|
2773
|
-
{ tenantDiscovery: migratorConfig.tenantDiscovery },
|
|
2774
|
-
{
|
|
2775
|
-
createPool: this.schemaManager.createPool.bind(this.schemaManager),
|
|
2776
|
-
schemaNameTemplate: tenantConfig.isolation.schemaNameTemplate,
|
|
2777
|
-
tenantSchema: tenantConfig.schemas.tenant
|
|
2778
|
-
}
|
|
2779
|
-
);
|
|
2780
|
-
this.syncManager = new SyncManager(
|
|
2781
|
-
{
|
|
2782
|
-
tenantDiscovery: migratorConfig.tenantDiscovery,
|
|
2783
|
-
migrationsFolder: migratorConfig.migrationsFolder,
|
|
2784
|
-
migrationsTable: this.migrationsTable
|
|
2785
|
-
},
|
|
2786
|
-
{
|
|
2787
|
-
createPool: this.schemaManager.createPool.bind(this.schemaManager),
|
|
2788
|
-
schemaNameTemplate: tenantConfig.isolation.schemaNameTemplate,
|
|
2789
|
-
migrationsTableExists: this.schemaManager.migrationsTableExists.bind(this.schemaManager),
|
|
2790
|
-
ensureMigrationsTable: this.schemaManager.ensureMigrationsTable.bind(this.schemaManager),
|
|
2791
|
-
getOrDetectFormat: this.getOrDetectFormat.bind(this),
|
|
2792
|
-
loadMigrations: this.loadMigrations.bind(this)
|
|
2793
|
-
}
|
|
2794
|
-
);
|
|
2795
|
-
this.migrationExecutor = new MigrationExecutor(
|
|
2796
|
-
{ hooks: migratorConfig.hooks },
|
|
2797
|
-
{
|
|
2798
|
-
createPool: this.schemaManager.createPool.bind(this.schemaManager),
|
|
2799
|
-
schemaNameTemplate: tenantConfig.isolation.schemaNameTemplate,
|
|
2800
|
-
migrationsTableExists: this.schemaManager.migrationsTableExists.bind(this.schemaManager),
|
|
2801
|
-
ensureMigrationsTable: this.schemaManager.ensureMigrationsTable.bind(this.schemaManager),
|
|
2802
|
-
getOrDetectFormat: this.getOrDetectFormat.bind(this),
|
|
2803
|
-
loadMigrations: this.loadMigrations.bind(this)
|
|
2804
|
-
}
|
|
2805
|
-
);
|
|
2806
|
-
this.batchExecutor = new BatchExecutor(
|
|
2807
|
-
{ tenantDiscovery: migratorConfig.tenantDiscovery },
|
|
2808
|
-
this.migrationExecutor,
|
|
2809
|
-
this.loadMigrations.bind(this)
|
|
2810
|
-
);
|
|
2811
|
-
this.cloner = new Cloner(
|
|
2812
|
-
{ migrationsTable: this.migrationsTable },
|
|
2813
|
-
{
|
|
2814
|
-
createPool: this.schemaManager.createPool.bind(this.schemaManager),
|
|
2815
|
-
createRootPool: this.schemaManager.createRootPool.bind(this.schemaManager),
|
|
2816
|
-
schemaNameTemplate: tenantConfig.isolation.schemaNameTemplate,
|
|
2817
|
-
schemaExists: this.schemaManager.schemaExists.bind(this.schemaManager),
|
|
2818
|
-
createSchema: this.schemaManager.createSchema.bind(this.schemaManager)
|
|
2819
|
-
}
|
|
2820
|
-
);
|
|
2821
|
-
}
|
|
2822
|
-
migrationsTable;
|
|
2823
|
-
schemaManager;
|
|
2824
|
-
driftDetector;
|
|
2825
|
-
seeder;
|
|
2826
|
-
syncManager;
|
|
2827
|
-
migrationExecutor;
|
|
2828
|
-
batchExecutor;
|
|
2829
|
-
cloner;
|
|
2830
|
-
/**
|
|
2831
|
-
* Migrate all tenants in parallel
|
|
2832
|
-
*
|
|
2833
|
-
* Delegates to BatchExecutor for parallel migration operations.
|
|
2834
|
-
*/
|
|
2835
|
-
async migrateAll(options = {}) {
|
|
2836
|
-
return this.batchExecutor.migrateAll(options);
|
|
2837
|
-
}
|
|
2838
|
-
/**
|
|
2839
|
-
* Migrate a single tenant
|
|
2840
|
-
*
|
|
2841
|
-
* Delegates to MigrationExecutor for single tenant operations.
|
|
2842
|
-
*/
|
|
2843
|
-
async migrateTenant(tenantId, migrations, options = {}) {
|
|
2844
|
-
return this.migrationExecutor.migrateTenant(tenantId, migrations, options);
|
|
2845
|
-
}
|
|
2846
|
-
/**
|
|
2847
|
-
* Migrate specific tenants
|
|
2848
|
-
*
|
|
2849
|
-
* Delegates to BatchExecutor for parallel migration operations.
|
|
2850
|
-
*/
|
|
2851
|
-
async migrateTenants(tenantIds, options = {}) {
|
|
2852
|
-
return this.batchExecutor.migrateTenants(tenantIds, options);
|
|
2853
|
-
}
|
|
2854
|
-
/**
|
|
2855
|
-
* Get migration status for all tenants
|
|
2856
|
-
*
|
|
2857
|
-
* Delegates to BatchExecutor for status operations.
|
|
2858
|
-
*/
|
|
2859
|
-
async getStatus() {
|
|
2860
|
-
return this.batchExecutor.getStatus();
|
|
2861
|
-
}
|
|
2862
|
-
/**
|
|
2863
|
-
* Get migration status for a specific tenant
|
|
2864
|
-
*
|
|
2865
|
-
* Delegates to MigrationExecutor for single tenant operations.
|
|
2866
|
-
*/
|
|
2867
|
-
async getTenantStatus(tenantId, migrations) {
|
|
2868
|
-
return this.migrationExecutor.getTenantStatus(tenantId, migrations);
|
|
2869
|
-
}
|
|
2870
|
-
/**
|
|
2871
|
-
* Create a new tenant schema and optionally apply migrations
|
|
2872
|
-
*/
|
|
2873
|
-
async createTenant(tenantId, options = {}) {
|
|
2874
|
-
const { migrate = true } = options;
|
|
2875
|
-
await this.schemaManager.createSchema(tenantId);
|
|
2876
|
-
if (migrate) {
|
|
2877
|
-
await this.migrateTenant(tenantId);
|
|
2878
|
-
}
|
|
2879
|
-
}
|
|
2880
|
-
/**
|
|
2881
|
-
* Drop a tenant schema
|
|
2882
|
-
*/
|
|
2883
|
-
async dropTenant(tenantId, options = {}) {
|
|
2884
|
-
await this.schemaManager.dropSchema(tenantId, options);
|
|
2885
|
-
}
|
|
2886
|
-
/**
|
|
2887
|
-
* Check if a tenant schema exists
|
|
2888
|
-
*/
|
|
2889
|
-
async tenantExists(tenantId) {
|
|
2890
|
-
return this.schemaManager.schemaExists(tenantId);
|
|
2891
|
-
}
|
|
2892
|
-
/**
|
|
2893
|
-
* Clone a tenant to a new tenant
|
|
2894
|
-
*
|
|
2895
|
-
* By default, clones only schema structure. Use includeData to copy data.
|
|
2896
|
-
*
|
|
2897
|
-
* @example
|
|
2898
|
-
* ```typescript
|
|
2899
|
-
* // Schema-only clone
|
|
2900
|
-
* await migrator.cloneTenant('production', 'dev');
|
|
2901
|
-
*
|
|
2902
|
-
* // Clone with data
|
|
2903
|
-
* await migrator.cloneTenant('production', 'dev', { includeData: true });
|
|
2904
|
-
*
|
|
2905
|
-
* // Clone with anonymization
|
|
2906
|
-
* await migrator.cloneTenant('production', 'dev', {
|
|
2907
|
-
* includeData: true,
|
|
2908
|
-
* anonymize: {
|
|
2909
|
-
* enabled: true,
|
|
2910
|
-
* rules: {
|
|
2911
|
-
* users: { email: null, phone: null },
|
|
2912
|
-
* },
|
|
2913
|
-
* },
|
|
2914
|
-
* });
|
|
2915
|
-
* ```
|
|
2916
|
-
*/
|
|
2917
|
-
async cloneTenant(sourceTenantId, targetTenantId, options = {}) {
|
|
2918
|
-
return this.cloner.cloneTenant(sourceTenantId, targetTenantId, options);
|
|
2919
|
-
}
|
|
2920
|
-
/**
|
|
2921
|
-
* Mark migrations as applied without executing SQL
|
|
2922
|
-
* Useful for syncing tracking state with already-applied migrations
|
|
2923
|
-
*
|
|
2924
|
-
* Delegates to MigrationExecutor for single tenant operations.
|
|
2925
|
-
*/
|
|
2926
|
-
async markAsApplied(tenantId, options = {}) {
|
|
2927
|
-
return this.migrationExecutor.markAsApplied(tenantId, options);
|
|
2928
|
-
}
|
|
2929
|
-
/**
|
|
2930
|
-
* Mark migrations as applied for all tenants without executing SQL
|
|
2931
|
-
* Useful for syncing tracking state with already-applied migrations
|
|
2932
|
-
*
|
|
2933
|
-
* Delegates to BatchExecutor for parallel operations.
|
|
2934
|
-
*/
|
|
2935
|
-
async markAllAsApplied(options = {}) {
|
|
2936
|
-
return this.batchExecutor.markAllAsApplied(options);
|
|
2937
|
-
}
|
|
2938
|
-
// ============================================================================
|
|
2939
|
-
// Sync Methods (delegated to SyncManager)
|
|
2940
|
-
// ============================================================================
|
|
2941
|
-
/**
|
|
2942
|
-
* Get sync status for all tenants
|
|
2943
|
-
* Detects divergences between migrations on disk and tracking in database
|
|
2944
|
-
*/
|
|
2945
|
-
async getSyncStatus() {
|
|
2946
|
-
return this.syncManager.getSyncStatus();
|
|
2947
|
-
}
|
|
2948
|
-
/**
|
|
2949
|
-
* Get sync status for a specific tenant
|
|
2950
|
-
*/
|
|
2951
|
-
async getTenantSyncStatus(tenantId, migrations) {
|
|
2952
|
-
return this.syncManager.getTenantSyncStatus(tenantId, migrations);
|
|
2953
|
-
}
|
|
2954
|
-
/**
|
|
2955
|
-
* Mark missing migrations as applied for a tenant
|
|
2956
|
-
*/
|
|
2957
|
-
async markMissing(tenantId) {
|
|
2958
|
-
return this.syncManager.markMissing(tenantId);
|
|
2959
|
-
}
|
|
2960
|
-
/**
|
|
2961
|
-
* Mark missing migrations as applied for all tenants
|
|
2962
|
-
*/
|
|
2963
|
-
async markAllMissing(options = {}) {
|
|
2964
|
-
return this.syncManager.markAllMissing(options);
|
|
2965
|
-
}
|
|
2966
|
-
/**
|
|
2967
|
-
* Remove orphan migration records for a tenant
|
|
2968
|
-
*/
|
|
2969
|
-
async cleanOrphans(tenantId) {
|
|
2970
|
-
return this.syncManager.cleanOrphans(tenantId);
|
|
2971
|
-
}
|
|
2972
|
-
/**
|
|
2973
|
-
* Remove orphan migration records for all tenants
|
|
2974
|
-
*/
|
|
2975
|
-
async cleanAllOrphans(options = {}) {
|
|
2976
|
-
return this.syncManager.cleanAllOrphans(options);
|
|
2977
|
-
}
|
|
2978
|
-
// ============================================================================
|
|
2979
|
-
// Seeding Methods (delegated to Seeder)
|
|
2980
|
-
// ============================================================================
|
|
2981
|
-
/**
|
|
2982
|
-
* Seed a single tenant with initial data
|
|
2983
|
-
*
|
|
2984
|
-
* @example
|
|
2985
|
-
* ```typescript
|
|
2986
|
-
* const seed: SeedFunction = async (db, tenantId) => {
|
|
2987
|
-
* await db.insert(roles).values([
|
|
2988
|
-
* { name: 'admin', permissions: ['*'] },
|
|
2989
|
-
* { name: 'user', permissions: ['read'] },
|
|
2990
|
-
* ]);
|
|
2991
|
-
* };
|
|
2992
|
-
*
|
|
2993
|
-
* await migrator.seedTenant('tenant-123', seed);
|
|
2994
|
-
* ```
|
|
2995
|
-
*/
|
|
2996
|
-
async seedTenant(tenantId, seedFn) {
|
|
2997
|
-
return this.seeder.seedTenant(tenantId, seedFn);
|
|
2998
|
-
}
|
|
2999
|
-
/**
|
|
3000
|
-
* Seed all tenants with initial data in parallel
|
|
3001
|
-
*
|
|
3002
|
-
* @example
|
|
3003
|
-
* ```typescript
|
|
3004
|
-
* const seed: SeedFunction = async (db, tenantId) => {
|
|
3005
|
-
* await db.insert(roles).values([
|
|
3006
|
-
* { name: 'admin', permissions: ['*'] },
|
|
3007
|
-
* ]);
|
|
3008
|
-
* };
|
|
3009
|
-
*
|
|
3010
|
-
* await migrator.seedAll(seed, { concurrency: 10 });
|
|
3011
|
-
* ```
|
|
3012
|
-
*/
|
|
3013
|
-
async seedAll(seedFn, options = {}) {
|
|
3014
|
-
return this.seeder.seedAll(seedFn, options);
|
|
3015
|
-
}
|
|
3016
|
-
/**
|
|
3017
|
-
* Seed specific tenants with initial data
|
|
3018
|
-
*/
|
|
3019
|
-
async seedTenants(tenantIds, seedFn, options = {}) {
|
|
3020
|
-
return this.seeder.seedTenants(tenantIds, seedFn, options);
|
|
3021
|
-
}
|
|
3022
|
-
/**
|
|
3023
|
-
* Load migration files from the migrations folder
|
|
3024
|
-
*/
|
|
3025
|
-
async loadMigrations() {
|
|
3026
|
-
const files = await readdir(this.migratorConfig.migrationsFolder);
|
|
3027
|
-
const migrations = [];
|
|
3028
|
-
for (const file of files) {
|
|
3029
|
-
if (!file.endsWith(".sql")) continue;
|
|
3030
|
-
const filePath = join(this.migratorConfig.migrationsFolder, file);
|
|
3031
|
-
const content = await readFile(filePath, "utf-8");
|
|
3032
|
-
const match = file.match(/^(\d+)_/);
|
|
3033
|
-
const timestamp = match?.[1] ? parseInt(match[1], 10) : 0;
|
|
3034
|
-
const hash = createHash("sha256").update(content).digest("hex");
|
|
3035
|
-
migrations.push({
|
|
3036
|
-
name: basename(file, ".sql"),
|
|
3037
|
-
path: filePath,
|
|
3038
|
-
sql: content,
|
|
3039
|
-
timestamp,
|
|
3040
|
-
hash
|
|
3041
|
-
});
|
|
3042
|
-
}
|
|
3043
|
-
return migrations.sort((a, b) => a.timestamp - b.timestamp);
|
|
3044
|
-
}
|
|
3045
|
-
/**
|
|
3046
|
-
* Get or detect the format for a schema
|
|
3047
|
-
* Returns the configured format or auto-detects from existing table
|
|
3048
|
-
*
|
|
3049
|
-
* Note: This method is shared with SyncManager and MigrationExecutor via dependency injection.
|
|
3050
|
-
*/
|
|
3051
|
-
async getOrDetectFormat(pool, schemaName) {
|
|
3052
|
-
const configuredFormat = this.migratorConfig.tableFormat ?? "auto";
|
|
3053
|
-
if (configuredFormat !== "auto") {
|
|
3054
|
-
return getFormatConfig(configuredFormat, this.migrationsTable);
|
|
3055
|
-
}
|
|
3056
|
-
const detected = await detectTableFormat(pool, schemaName, this.migrationsTable);
|
|
3057
|
-
if (detected) {
|
|
3058
|
-
return detected;
|
|
3059
|
-
}
|
|
3060
|
-
const defaultFormat = this.migratorConfig.defaultFormat ?? "name";
|
|
3061
|
-
return getFormatConfig(defaultFormat, this.migrationsTable);
|
|
3062
|
-
}
|
|
3063
|
-
// ============================================================================
|
|
3064
|
-
// Schema Drift Detection Methods (delegated to DriftDetector)
|
|
3065
|
-
// ============================================================================
|
|
3066
|
-
/**
|
|
3067
|
-
* Detect schema drift across all tenants
|
|
3068
|
-
* Compares each tenant's schema against a reference tenant (first tenant by default)
|
|
3069
|
-
*
|
|
3070
|
-
* @example
|
|
3071
|
-
* ```typescript
|
|
3072
|
-
* const drift = await migrator.getSchemaDrift();
|
|
3073
|
-
* if (drift.withDrift > 0) {
|
|
3074
|
-
* console.log('Schema drift detected!');
|
|
3075
|
-
* for (const tenant of drift.details) {
|
|
3076
|
-
* if (tenant.hasDrift) {
|
|
3077
|
-
* console.log(`Tenant ${tenant.tenantId} has drift:`);
|
|
3078
|
-
* for (const table of tenant.tables) {
|
|
3079
|
-
* for (const col of table.columns) {
|
|
3080
|
-
* console.log(` - ${table.table}.${col.column}: ${col.description}`);
|
|
3081
|
-
* }
|
|
3082
|
-
* }
|
|
3083
|
-
* }
|
|
3084
|
-
* }
|
|
3085
|
-
* }
|
|
3086
|
-
* ```
|
|
3087
|
-
*/
|
|
3088
|
-
async getSchemaDrift(options = {}) {
|
|
3089
|
-
return this.driftDetector.detectDrift(options);
|
|
3090
|
-
}
|
|
3091
|
-
/**
|
|
3092
|
-
* Get schema drift for a specific tenant compared to a reference
|
|
3093
|
-
*/
|
|
3094
|
-
async getTenantSchemaDrift(tenantId, referenceTenantId, options = {}) {
|
|
3095
|
-
return this.driftDetector.compareTenant(tenantId, referenceTenantId, options);
|
|
3096
|
-
}
|
|
3097
|
-
/**
|
|
3098
|
-
* Introspect the schema of a tenant
|
|
3099
|
-
*/
|
|
3100
|
-
async introspectTenantSchema(tenantId, options = {}) {
|
|
3101
|
-
return this.driftDetector.introspectSchema(tenantId, options);
|
|
3102
|
-
}
|
|
3103
|
-
};
|
|
3104
|
-
function createMigrator(tenantConfig, migratorConfig) {
|
|
3105
|
-
return new Migrator(tenantConfig, migratorConfig);
|
|
3106
|
-
}
|
|
3107
|
-
|
|
3108
|
-
export { BatchExecutor, Cloner, DEFAULT_FORMAT, DRIZZLE_KIT_FORMAT, MigrationExecutor, Migrator, SchemaManager, Seeder, SyncManager, createBatchExecutor, createCloner, createMigrationExecutor, createMigrator, createSchemaManager, createSeeder, createSyncManager, detectTableFormat, getFormatConfig };
|
|
3109
|
-
//# sourceMappingURL=index.js.map
|
|
3110
|
-
//# sourceMappingURL=index.js.map
|
|
152
|
+
AND tc.table_name != ccu.table_name`,[e]),r=new Map,t=new Set(n);for(let c of n)r.set(c,new Set);for(let c of a.rows)t.has(c.table_name)&&t.has(c.foreign_table_name)&&r.get(c.table_name).add(c.foreign_table_name);let i=[],s=new Map,o=[];for(let c of n)s.set(c,0);for(let[c,u]of r)for(let g of u)s.set(g,(s.get(g)??0)+1);for(let[c,u]of s)u===0&&o.push(c);for(;o.length>0;){let c=o.shift();i.push(c);for(let[u,g]of r)if(g.has(c)){g.delete(c);let p=(s.get(u)??0)-1;s.set(u,p),p===0&&o.push(u);}}let l=n.filter(c=>!i.includes(c));return [...i,...l]}async function K(m,e,n,a,r,t){let i=0,s=await be(m,e,a);await m.query("SET session_replication_role = replica");try{for(let o=0;o<s.length;o++){let l=s[o];t?.("copying_data",{table:l,progress:o+1,total:s.length});let c=await Ee(m,e,n,l,r);i+=c;}}finally{await m.query("SET session_replication_role = DEFAULT");}return i}var we="__drizzle_migrations",_=class{constructor(e,n){this.deps=n;this.migrationsTable=e.migrationsTable??we;}migrationsTable;async cloneTenant(e,n,a={}){let r=Date.now(),{includeData:t=false,anonymize:i,excludeTables:s=[],onProgress:o}=a,l=this.deps.schemaNameTemplate(e),c=this.deps.schemaNameTemplate(n),u=[this.migrationsTable,...s],g=null,p=null;try{if(o?.("starting"),!await this.deps.schemaExists(e))return this.createErrorResult(e,n,c,`Source tenant "${e}" does not exist`,r);if(await this.deps.schemaExists(n))return this.createErrorResult(e,n,c,`Target tenant "${n}" already exists`,r);o?.("introspecting"),g=await this.deps.createPool(l);let d=await Y(g,l,u);if(d.length===0)return o?.("creating_schema"),await this.deps.createSchema(n),o?.("completed"),{sourceTenant:e,targetTenant:n,targetSchema:c,success:!0,tables:[],durationMs:Date.now()-r};let f=await Promise.all(d.map(S=>W(g,l,c,S)));await g.end(),g=null,o?.("creating_schema"),await this.deps.createSchema(n),p=await this.deps.createRootPool(),o?.("creating_tables");for(let S of f)await p.query(`SET search_path TO "${c}"; ${S.createDdl}`);o?.("creating_constraints");for(let S of f)for(let C of S.constraintDdls.filter(b=>!b.includes("FOREIGN KEY")))try{await p.query(`SET search_path TO "${c}"; ${C}`);}catch{}o?.("creating_indexes");for(let S of f)for(let C of S.indexDdls)try{await p.query(C);}catch{}let P=0;t&&(o?.("copying_data"),P=await K(p,l,c,d,i?.enabled?i.rules:void 0,o));for(let S of f)for(let C of S.constraintDdls.filter(b=>b.includes("FOREIGN KEY")))try{await p.query(C);}catch{}o?.("completed");let $={sourceTenant:e,targetTenant:n,targetSchema:c,success:!0,tables:d,durationMs:Date.now()-r};return t&&($.rowsCopied=P),$}catch(h){return a.onError?.(h),o?.("failed"),this.createErrorResult(e,n,c,h.message,r)}finally{g&&await g.end().catch(()=>{}),p&&await p.end().catch(()=>{});}}createErrorResult(e,n,a,r,t){return {sourceTenant:e,targetTenant:n,targetSchema:a,success:false,error:r,tables:[],durationMs:Date.now()-t}}};function V(m,e){return new _(m,e)}var De="public",E=class{constructor(e,n){this.config=e;this.deps=n;this.schemaName=e.schemaName??De;}schemaName;async migrate(e={}){let n=Date.now(),a=[],r=await this.deps.createPool();try{e.onProgress?.("starting"),await this.config.hooks?.beforeMigration?.();let t=await this.deps.getOrDetectFormat(r,this.schemaName);await this.deps.ensureMigrationsTable(r,this.schemaName,t);let i=await this.deps.loadMigrations(),s=await this.getAppliedMigrations(r,t),o=new Set(s.map(c=>c.identifier)),l=i.filter(c=>!this.isMigrationApplied(c,o,t));if(e.dryRun)return {schemaName:this.schemaName,success:!0,appliedMigrations:l.map(c=>c.name),durationMs:Date.now()-n,format:t.format};for(let c of l){let u=Date.now();e.onProgress?.("migrating",c.name),await this.applyMigration(r,c,t),await this.config.hooks?.afterMigration?.(c.name,Date.now()-u),a.push(c.name);}return e.onProgress?.("completed"),{schemaName:this.schemaName,success:!0,appliedMigrations:a,durationMs:Date.now()-n,format:t.format}}catch(t){return e.onProgress?.("failed"),{schemaName:this.schemaName,success:false,appliedMigrations:a,error:t.message,durationMs:Date.now()-n}}finally{await r.end();}}async markAsApplied(e={}){let n=Date.now(),a=[],r=await this.deps.createPool();try{e.onProgress?.("starting");let t=await this.deps.getOrDetectFormat(r,this.schemaName);await this.deps.ensureMigrationsTable(r,this.schemaName,t);let i=await this.deps.loadMigrations(),s=await this.getAppliedMigrations(r,t),o=new Set(s.map(c=>c.identifier)),l=i.filter(c=>!this.isMigrationApplied(c,o,t));for(let c of l)e.onProgress?.("migrating",c.name),await this.recordMigration(r,c,t),a.push(c.name);return e.onProgress?.("completed"),{schemaName:this.schemaName,success:!0,appliedMigrations:a,durationMs:Date.now()-n,format:t.format}}catch(t){return e.onProgress?.("failed"),{schemaName:this.schemaName,success:false,appliedMigrations:a,error:t.message,durationMs:Date.now()-n}}finally{await r.end();}}async getStatus(){let e=await this.deps.createPool();try{let n=await this.deps.loadMigrations();if(!await this.deps.migrationsTableExists(e,this.schemaName))return {schemaName:this.schemaName,appliedCount:0,pendingCount:n.length,pendingMigrations:n.map(o=>o.name),status:n.length>0?"behind":"ok",format:null};let r=await this.deps.getOrDetectFormat(e,this.schemaName),t=await this.getAppliedMigrations(e,r),i=new Set(t.map(o=>o.identifier)),s=n.filter(o=>!this.isMigrationApplied(o,i,r));return {schemaName:this.schemaName,appliedCount:t.length,pendingCount:s.length,pendingMigrations:s.map(o=>o.name),status:s.length>0?"behind":"ok",format:r.format}}catch(n){return {schemaName:this.schemaName,appliedCount:0,pendingCount:0,pendingMigrations:[],status:"error",error:n.message,format:null}}finally{await e.end();}}async getAppliedMigrations(e,n){let a=n.columns.identifier,r=n.columns.timestamp;return (await e.query(`SELECT id, "${a}" as identifier, "${r}" as applied_at
|
|
153
|
+
FROM "${this.schemaName}"."${n.tableName}"
|
|
154
|
+
ORDER BY id`)).rows.map(i=>{let s=n.columns.timestampType==="bigint"?new Date(Number(i.applied_at)):new Date(i.applied_at);return {identifier:i.identifier,...n.columns.identifier==="name"?{name:i.identifier}:{hash:i.identifier},appliedAt:s}})}isMigrationApplied(e,n,a){return a.columns.identifier==="name"?n.has(e.name):n.has(e.hash)||n.has(e.name)}async applyMigration(e,n,a){let r=await e.connect();try{await r.query("BEGIN"),await r.query(n.sql);let{identifier:t,timestamp:i,timestampType:s}=a.columns,o=t==="name"?n.name:n.hash,l=s==="bigint"?Date.now():new Date;await r.query(`INSERT INTO "${this.schemaName}"."${a.tableName}" ("${t}", "${i}") VALUES ($1, $2)`,[o,l]),await r.query("COMMIT");}catch(t){throw await r.query("ROLLBACK"),t}finally{r.release();}}async recordMigration(e,n,a){let{identifier:r,timestamp:t,timestampType:i}=a.columns,s=r==="name"?n.name:n.hash,o=i==="bigint"?Date.now():new Date;await e.query(`INSERT INTO "${this.schemaName}"."${a.tableName}" ("${r}", "${t}") VALUES ($1, $2)`,[s,o]);}};function G(m,e){return new E(m,e)}var xe="__drizzle_migrations",te="__drizzle_shared_migrations",F=class{constructor(e,n){this.migratorConfig=n;if(this.migrationsTable=n.migrationsTable??xe,this.schemaManager=new D(e,this.migrationsTable),this.driftDetector=new O(e,this.schemaManager,{migrationsTable:this.migrationsTable,tenantDiscovery:n.tenantDiscovery}),this.seeder=new R({tenantDiscovery:n.tenantDiscovery},{createPool:this.schemaManager.createPool.bind(this.schemaManager),schemaNameTemplate:e.isolation.schemaNameTemplate,tenantSchema:e.schemas.tenant}),this.syncManager=new x({tenantDiscovery:n.tenantDiscovery,migrationsFolder:n.migrationsFolder,migrationsTable:this.migrationsTable},{createPool:this.schemaManager.createPool.bind(this.schemaManager),schemaNameTemplate:e.isolation.schemaNameTemplate,migrationsTableExists:this.schemaManager.migrationsTableExists.bind(this.schemaManager),ensureMigrationsTable:this.schemaManager.ensureMigrationsTable.bind(this.schemaManager),getOrDetectFormat:this.getOrDetectFormat.bind(this),loadMigrations:this.loadMigrations.bind(this)}),this.migrationExecutor=new T({hooks:n.hooks},{createPool:this.schemaManager.createPool.bind(this.schemaManager),schemaNameTemplate:e.isolation.schemaNameTemplate,migrationsTableExists:this.schemaManager.migrationsTableExists.bind(this.schemaManager),ensureMigrationsTable:this.schemaManager.ensureMigrationsTable.bind(this.schemaManager),getOrDetectFormat:this.getOrDetectFormat.bind(this),loadMigrations:this.loadMigrations.bind(this)}),this.batchExecutor=new M({tenantDiscovery:n.tenantDiscovery},this.migrationExecutor,this.loadMigrations.bind(this)),this.cloner=new _({migrationsTable:this.migrationsTable},{createPool:this.schemaManager.createPool.bind(this.schemaManager),createRootPool:this.schemaManager.createRootPool.bind(this.schemaManager),schemaNameTemplate:e.isolation.schemaNameTemplate,schemaExists:this.schemaManager.schemaExists.bind(this.schemaManager),createSchema:this.schemaManager.createSchema.bind(this.schemaManager)}),n.sharedMigrationsFolder&&existsSync(n.sharedMigrationsFolder)){let a=n.sharedMigrationsTable??te,r=n.sharedHooks,t={schemaName:"public",migrationsTable:a};(r?.beforeMigration||r?.afterApply)&&(t.hooks={},r.beforeMigration&&(t.hooks.beforeMigration=r.beforeMigration),r.afterApply&&(t.hooks.afterMigration=r.afterApply)),this.sharedMigrationExecutor=new E(t,{createPool:this.schemaManager.createRootPool.bind(this.schemaManager),migrationsTableExists:this.schemaManager.migrationsTableExists.bind(this.schemaManager),ensureMigrationsTable:this.schemaManager.ensureMigrationsTable.bind(this.schemaManager),getOrDetectFormat:this.getOrDetectSharedFormat.bind(this),loadMigrations:this.loadSharedMigrations.bind(this)});}else this.sharedMigrationExecutor=null;e.schemas.shared?this.sharedSeeder=new A({schemaName:"public"},{createPool:this.schemaManager.createRootPool.bind(this.schemaManager),sharedSchema:e.schemas.shared}):this.sharedSeeder=null;}migrationsTable;schemaManager;driftDetector;seeder;syncManager;migrationExecutor;batchExecutor;cloner;sharedMigrationExecutor;sharedSeeder;async migrateAll(e={}){return this.batchExecutor.migrateAll(e)}async migrateTenant(e,n,a={}){return this.migrationExecutor.migrateTenant(e,n,a)}async migrateTenants(e,n={}){return this.batchExecutor.migrateTenants(e,n)}async getStatus(){return this.batchExecutor.getStatus()}async getTenantStatus(e,n){return this.migrationExecutor.getTenantStatus(e,n)}async createTenant(e,n={}){let{migrate:a=true}=n;await this.schemaManager.createSchema(e),a&&await this.migrateTenant(e);}async dropTenant(e,n={}){await this.schemaManager.dropSchema(e,n);}async tenantExists(e){return this.schemaManager.schemaExists(e)}async cloneTenant(e,n,a={}){return this.cloner.cloneTenant(e,n,a)}async markAsApplied(e,n={}){return this.migrationExecutor.markAsApplied(e,n)}async markAllAsApplied(e={}){return this.batchExecutor.markAllAsApplied(e)}async getSyncStatus(){return this.syncManager.getSyncStatus()}async getTenantSyncStatus(e,n){return this.syncManager.getTenantSyncStatus(e,n)}async markMissing(e){return this.syncManager.markMissing(e)}async markAllMissing(e={}){return this.syncManager.markAllMissing(e)}async cleanOrphans(e){return this.syncManager.cleanOrphans(e)}async cleanAllOrphans(e={}){return this.syncManager.cleanAllOrphans(e)}async seedTenant(e,n){return this.seeder.seedTenant(e,n)}async seedAll(e,n={}){return this.seeder.seedAll(e,n)}async seedTenants(e,n,a={}){return this.seeder.seedTenants(e,n,a)}hasSharedSeeding(){return this.sharedSeeder!==null}async seedShared(e){return this.sharedSeeder?this.sharedSeeder.seed(e):{schemaName:"public",success:false,error:"Shared schema not configured. Set schemas.shared in tenant config.",durationMs:0}}async seedAllWithShared(e,n,a={}){let r=await this.seedShared(e),t=await this.seedAll(n,a);return {shared:r,tenants:t}}async loadMigrations(){let e=await readdir(this.migratorConfig.migrationsFolder),n=[];for(let a of e){if(!a.endsWith(".sql"))continue;let r=join(this.migratorConfig.migrationsFolder,a),t=await readFile(r,"utf-8"),i=a.match(/^(\d+)_/),s=i?.[1]?parseInt(i[1],10):0,o=createHash("sha256").update(t).digest("hex");n.push({name:basename(a,".sql"),path:r,sql:t,timestamp:s,hash:o});}return n.sort((a,r)=>a.timestamp-r.timestamp)}async getOrDetectFormat(e,n){let a=this.migratorConfig.tableFormat??"auto";if(a!=="auto")return w(a,this.migrationsTable);let r=await N(e,n,this.migrationsTable);if(r)return r;let t=this.migratorConfig.defaultFormat??"name";return w(t,this.migrationsTable)}async loadSharedMigrations(){if(!this.migratorConfig.sharedMigrationsFolder)return [];let e=await readdir(this.migratorConfig.sharedMigrationsFolder),n=[];for(let a of e){if(!a.endsWith(".sql"))continue;let r=join(this.migratorConfig.sharedMigrationsFolder,a),t=await readFile(r,"utf-8"),i=a.match(/^(\d+)_/),s=i?.[1]?parseInt(i[1],10):0,o=createHash("sha256").update(t).digest("hex");n.push({name:basename(a,".sql"),path:r,sql:t,timestamp:s,hash:o});}return n.sort((a,r)=>a.timestamp-r.timestamp)}async getOrDetectSharedFormat(e,n){let a=this.migratorConfig.sharedMigrationsTable??te,r=this.migratorConfig.sharedTableFormat??this.migratorConfig.tableFormat??"auto";if(r!=="auto")return w(r,a);let t=await N(e,n,a);if(t)return t;let i=this.migratorConfig.sharedDefaultFormat??this.migratorConfig.defaultFormat??"name";return w(i,a)}hasSharedMigrations(){return this.sharedMigrationExecutor!==null}async migrateShared(e={}){return this.sharedMigrationExecutor?this.sharedMigrationExecutor.migrate(e):{schemaName:"public",success:false,appliedMigrations:[],error:"Shared migrations not configured. Set sharedMigrationsFolder in migrator config.",durationMs:0}}async getSharedStatus(){return this.sharedMigrationExecutor?this.sharedMigrationExecutor.getStatus():{schemaName:"public",appliedCount:0,pendingCount:0,pendingMigrations:[],status:"error",error:"Shared migrations not configured. Set sharedMigrationsFolder in migrator config.",format:null}}async markSharedAsApplied(e={}){return this.sharedMigrationExecutor?this.sharedMigrationExecutor.markAsApplied(e):{schemaName:"public",success:false,appliedMigrations:[],error:"Shared migrations not configured. Set sharedMigrationsFolder in migrator config.",durationMs:0}}async migrateAllWithShared(e={}){let{sharedOptions:n,...a}=e,r=await this.migrateShared(n??{}),t=await this.migrateAll(a);return {shared:r,tenants:t}}async getSchemaDrift(e={}){return this.driftDetector.detectDrift(e)}async getTenantSchemaDrift(e,n,a={}){return this.driftDetector.compareTenant(e,n,a)}async introspectTenantSchema(e,n={}){return this.driftDetector.introspectSchema(e,n)}};function Ce(m,e){return new F(m,e)}export{M as BatchExecutor,_ as Cloner,ne as DEFAULT_FORMAT,ae as DRIZZLE_KIT_FORMAT,T as MigrationExecutor,F as Migrator,D as SchemaManager,R as Seeder,E as SharedMigrationExecutor,x as SyncManager,H as createBatchExecutor,V as createCloner,U as createMigrationExecutor,Ce as createMigrator,ie as createSchemaManager,ce as createSeeder,G as createSharedMigrationExecutor,ue as createSyncManager,N as detectTableFormat,w as getFormatConfig};
|