appwrite-utils-cli 1.7.9 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +14 -199
  2. package/README.md +87 -30
  3. package/dist/adapters/AdapterFactory.js +5 -25
  4. package/dist/adapters/DatabaseAdapter.d.ts +17 -2
  5. package/dist/adapters/LegacyAdapter.d.ts +2 -1
  6. package/dist/adapters/LegacyAdapter.js +212 -16
  7. package/dist/adapters/TablesDBAdapter.d.ts +2 -12
  8. package/dist/adapters/TablesDBAdapter.js +261 -57
  9. package/dist/cli/commands/databaseCommands.js +4 -3
  10. package/dist/cli/commands/functionCommands.js +17 -8
  11. package/dist/collections/attributes.js +447 -125
  12. package/dist/collections/methods.js +197 -186
  13. package/dist/collections/tableOperations.d.ts +86 -0
  14. package/dist/collections/tableOperations.js +434 -0
  15. package/dist/collections/transferOperations.d.ts +3 -2
  16. package/dist/collections/transferOperations.js +93 -12
  17. package/dist/config/yamlConfig.d.ts +221 -88
  18. package/dist/examples/yamlTerminologyExample.d.ts +1 -1
  19. package/dist/examples/yamlTerminologyExample.js +6 -3
  20. package/dist/functions/fnConfigDiscovery.d.ts +3 -0
  21. package/dist/functions/fnConfigDiscovery.js +108 -0
  22. package/dist/interactiveCLI.js +18 -15
  23. package/dist/main.js +211 -73
  24. package/dist/migrations/appwriteToX.d.ts +88 -23
  25. package/dist/migrations/comprehensiveTransfer.d.ts +2 -0
  26. package/dist/migrations/comprehensiveTransfer.js +83 -6
  27. package/dist/migrations/dataLoader.d.ts +227 -69
  28. package/dist/migrations/dataLoader.js +3 -3
  29. package/dist/migrations/importController.js +3 -3
  30. package/dist/migrations/relationships.d.ts +8 -2
  31. package/dist/migrations/services/ImportOrchestrator.js +3 -3
  32. package/dist/migrations/transfer.js +159 -37
  33. package/dist/shared/attributeMapper.d.ts +20 -0
  34. package/dist/shared/attributeMapper.js +203 -0
  35. package/dist/shared/selectionDialogs.js +8 -4
  36. package/dist/storage/schemas.d.ts +354 -92
  37. package/dist/utils/configDiscovery.js +4 -3
  38. package/dist/utils/versionDetection.d.ts +0 -4
  39. package/dist/utils/versionDetection.js +41 -173
  40. package/dist/utils/yamlConverter.js +89 -16
  41. package/dist/utils/yamlLoader.d.ts +1 -1
  42. package/dist/utils/yamlLoader.js +6 -2
  43. package/dist/utilsController.js +56 -19
  44. package/package.json +4 -4
  45. package/src/adapters/AdapterFactory.ts +119 -143
  46. package/src/adapters/DatabaseAdapter.ts +18 -3
  47. package/src/adapters/LegacyAdapter.ts +236 -105
  48. package/src/adapters/TablesDBAdapter.ts +773 -643
  49. package/src/cli/commands/databaseCommands.ts +13 -12
  50. package/src/cli/commands/functionCommands.ts +23 -14
  51. package/src/collections/attributes.ts +2054 -1611
  52. package/src/collections/methods.ts +208 -293
  53. package/src/collections/tableOperations.ts +506 -0
  54. package/src/collections/transferOperations.ts +218 -144
  55. package/src/examples/yamlTerminologyExample.ts +10 -5
  56. package/src/functions/fnConfigDiscovery.ts +103 -0
  57. package/src/interactiveCLI.ts +25 -20
  58. package/src/main.ts +549 -194
  59. package/src/migrations/comprehensiveTransfer.ts +126 -50
  60. package/src/migrations/dataLoader.ts +3 -3
  61. package/src/migrations/importController.ts +3 -3
  62. package/src/migrations/services/ImportOrchestrator.ts +3 -3
  63. package/src/migrations/transfer.ts +148 -131
  64. package/src/shared/attributeMapper.ts +229 -0
  65. package/src/shared/selectionDialogs.ts +29 -25
  66. package/src/utils/configDiscovery.ts +9 -3
  67. package/src/utils/versionDetection.ts +74 -228
  68. package/src/utils/yamlConverter.ts +94 -17
  69. package/src/utils/yamlLoader.ts +11 -4
  70. package/src/utilsController.ts +80 -30
@@ -0,0 +1,506 @@
1
+ import type { Attribute } from "appwrite-utils";
2
+ import { mapToCreateAttributeParams, mapToUpdateAttributeParams } from "../shared/attributeMapper.js";
3
+ import { Decimal } from "decimal.js";
4
+ const EXTREME_BOUND = new Decimal('1e12');
5
+
6
+ // Enhanced change detection interfaces
7
+ interface ColumnPropertyChange {
8
+ property: string;
9
+ oldValue: any;
10
+ newValue: any;
11
+ requiresRecreate: boolean;
12
+ }
13
+
14
+ interface ColumnChangeAnalysis {
15
+ columnKey: string;
16
+ columnType: string;
17
+ hasChanges: boolean;
18
+ requiresRecreate: boolean;
19
+ changes: ColumnPropertyChange[];
20
+ mutableChanges: Record<string, { old: any; new: any }>;
21
+ immutableChanges: Record<string, { old: any; new: any }>;
22
+ }
23
+
24
+ interface ColumnOperationPlan {
25
+ toCreate: Attribute[];
26
+ toUpdate: Array<{ attribute: Attribute; changes: ColumnPropertyChange[] }>;
27
+ toRecreate: Array<{ oldAttribute: any; newAttribute: Attribute }>;
28
+ toDelete: Array<{ attribute: any }>;
29
+ unchanged: string[];
30
+ }
31
+
32
+ // Property configuration for different column types
33
+ const MUTABLE_PROPERTIES = {
34
+ string: ["required", "default", "size", "array"],
35
+ integer: ["required", "default", "min", "max", "array"],
36
+ float: ["required", "default", "min", "max", "array"],
37
+ double: ["required", "default", "min", "max", "array"],
38
+ boolean: ["required", "default", "array"],
39
+ datetime: ["required", "default", "array"],
40
+ email: ["required", "default", "array"],
41
+ ip: ["required", "default", "array"],
42
+ url: ["required", "default", "array"],
43
+ enum: ["required", "default", "elements", "array"],
44
+ relationship: ["required", "default"],
45
+ } as const;
46
+
47
+ const IMMUTABLE_PROPERTIES = {
48
+ string: ["encrypt", "key"],
49
+ integer: ["encrypt", "key"],
50
+ float: ["encrypt", "key"],
51
+ double: ["encrypt", "key"],
52
+ boolean: ["key"],
53
+ datetime: ["key"],
54
+ email: ["key"],
55
+ ip: ["key"],
56
+ url: ["key"],
57
+ enum: ["key"],
58
+ relationship: ["key", "relatedCollection", "relationType", "twoWay", "twoWayKey", "onDelete"],
59
+ } as const;
60
+
61
+ const TYPE_CHANGE_REQUIRES_RECREATE = [
62
+ "string",
63
+ "integer",
64
+ "float",
65
+ "double",
66
+ "boolean",
67
+ "datetime",
68
+ "email",
69
+ "ip",
70
+ "url",
71
+ "enum",
72
+ "relationship",
73
+ ];
74
+
75
+ type ComparableColumn = {
76
+ key: string;
77
+ type: string;
78
+ required?: boolean;
79
+ array?: boolean;
80
+ default?: any;
81
+ size?: number;
82
+ min?: number;
83
+ max?: number;
84
+ elements?: string[];
85
+ encrypt?: boolean;
86
+ // Relationship
87
+ relatedCollection?: string;
88
+ relationType?: string;
89
+ twoWay?: boolean;
90
+ twoWayKey?: string;
91
+ onDelete?: string;
92
+ side?: string;
93
+ };
94
+
95
+ function normDefault(val: any): any {
96
+ // Treat undefined and null as equal unset default
97
+ return val === undefined ? null : val;
98
+ }
99
+
100
+ function toNumber(n: any): number | undefined {
101
+ if (n === null || n === undefined) return undefined;
102
+ const num = Number(n);
103
+ return Number.isFinite(num) ? num : undefined;
104
+ }
105
+
106
+ export function normalizeAttributeToComparable(attr: Attribute): ComparableColumn {
107
+ const t = String((attr as any).type || '').toLowerCase();
108
+ const base: ComparableColumn = {
109
+ key: (attr as any).key,
110
+ type: t,
111
+ required: !!(attr as any).required,
112
+ array: !!(attr as any).array,
113
+ default: normDefault((attr as any).xdefault),
114
+ };
115
+
116
+ if (t === 'string') {
117
+ base.size = (attr as any).size ?? 255;
118
+ base.encrypt = !!((attr as any).encrypted ?? (attr as any).encrypt);
119
+ }
120
+ if (t === 'integer' || t === 'float' || t === 'double') {
121
+ const min = toNumber((attr as any).min);
122
+ const max = toNumber((attr as any).max);
123
+ if (min !== undefined && max !== undefined) {
124
+ base.min = Math.min(min, max);
125
+ base.max = Math.max(min, max);
126
+ } else {
127
+ base.min = min;
128
+ base.max = max;
129
+ }
130
+ }
131
+ if (t === 'enum') {
132
+ base.elements = Array.isArray((attr as any).elements) ? (attr as any).elements.slice().sort() : [];
133
+ }
134
+ if (t === 'relationship') {
135
+ base.relatedCollection = (attr as any).relatedCollection;
136
+ base.relationType = (attr as any).relationType;
137
+ base.twoWay = !!(attr as any).twoWay;
138
+ base.twoWayKey = (attr as any).twoWayKey;
139
+ base.onDelete = (attr as any).onDelete;
140
+ base.side = (attr as any).side;
141
+ }
142
+ return base;
143
+ }
144
+
145
+ export function normalizeColumnToComparable(col: any): ComparableColumn {
146
+ // Detect enum surfaced as string+elements from server and normalize to enum for comparison
147
+ let t = String((col?.type ?? col?.columnType ?? '')).toLowerCase();
148
+ const hasElements = Array.isArray(col?.elements) && (col.elements as any[]).length > 0;
149
+ if (t === 'string' && hasElements) t = 'enum';
150
+ const base: ComparableColumn = {
151
+ key: col?.key,
152
+ type: t,
153
+ required: !!col?.required,
154
+ array: !!col?.array,
155
+ default: normDefault(col?.default ?? col?.xdefault),
156
+ };
157
+
158
+ if (t === 'string') {
159
+ base.size = typeof col?.size === 'number' ? col.size : undefined;
160
+ base.encrypt = !!col?.encrypt;
161
+ }
162
+ if (t === 'integer' || t === 'float' || t === 'double') {
163
+ // Preserve raw min/max without forcing extremes; compare with Decimal in shallowEqual
164
+ const rawMin = (col as any)?.min;
165
+ const rawMax = (col as any)?.max;
166
+ base.min = rawMin as any;
167
+ base.max = rawMax as any;
168
+ }
169
+ if (t === 'enum') {
170
+ base.elements = Array.isArray(col?.elements) ? col.elements.slice().sort() : [];
171
+ }
172
+ if (t === 'relationship') {
173
+ base.relatedCollection = col?.relatedTableId || col?.relatedCollection;
174
+ base.relationType = col?.relationType || col?.typeName;
175
+ base.twoWay = !!col?.twoWay;
176
+ base.twoWayKey = col?.twoWayKey;
177
+ base.onDelete = col?.onDelete;
178
+ base.side = col?.side;
179
+ }
180
+ return base;
181
+ }
182
+
183
+ function shallowEqual(a: ComparableColumn, b: ComparableColumn): boolean {
184
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
185
+ for (const k of keys) {
186
+ const va: any = (a as any)[k];
187
+ const vb: any = (b as any)[k];
188
+ if (Array.isArray(va) && Array.isArray(vb)) {
189
+ if (va.length !== vb.length) return false;
190
+ for (let i = 0; i < va.length; i++) if (va[i] !== vb[i]) return false;
191
+ } else if (k === 'min' || k === 'max') {
192
+ // Compare numeric bounds with Decimal to avoid precision issues
193
+ if (va == null && vb == null) continue;
194
+ if (va == null || vb == null) {
195
+ // Treat extreme bounds on one side as equivalent to undefined (unbounded)
196
+ const present = va == null ? vb : va;
197
+ try {
198
+ const dp = new Decimal(String(present));
199
+ if (dp.abs().greaterThanOrEqualTo(EXTREME_BOUND)) continue; // equal
200
+ } catch {}
201
+ return false;
202
+ }
203
+ try {
204
+ const da = new Decimal(String(va));
205
+ const db = new Decimal(String(vb));
206
+ if (!da.equals(db)) return false;
207
+ } catch {
208
+ if (va !== vb) return false;
209
+ }
210
+ } else if (va !== vb) {
211
+ // Treat null and undefined as equal for defaults
212
+ if (!(va == null && vb == null)) return false;
213
+ }
214
+ }
215
+ return true;
216
+ }
217
+
218
+ export function isColumnEqualToColumn(a: any, b: any): boolean {
219
+ const na = normalizeColumnToComparable(a);
220
+ const nb = normalizeColumnToComparable(b);
221
+ return shallowEqual(na, nb);
222
+ }
223
+
224
+ export function isIndexEqualToIndex(a: any, b: any): boolean {
225
+ if (!a || !b) return false;
226
+ if (a.key !== b.key) return false;
227
+ if (String(a.type).toLowerCase() !== String(b.type).toLowerCase()) return false;
228
+
229
+ // Compare attributes as sets (order-insensitive)
230
+ const attrsA = Array.isArray(a.attributes) ? [...a.attributes].sort() : [];
231
+ const attrsB = Array.isArray(b.attributes) ? [...b.attributes].sort() : [];
232
+ if (attrsA.length !== attrsB.length) return false;
233
+ for (let i = 0; i < attrsA.length; i++) if (attrsA[i] !== attrsB[i]) return false;
234
+
235
+ // Orders are only considered if BOTH have orders defined
236
+ const hasOrdersA = Array.isArray(a.orders) && a.orders.length > 0;
237
+ const hasOrdersB = Array.isArray(b.orders) && b.orders.length > 0;
238
+ if (hasOrdersA && hasOrdersB) {
239
+ const ordersA = [...a.orders].sort();
240
+ const ordersB = [...b.orders].sort();
241
+ if (ordersA.length !== ordersB.length) return false;
242
+ for (let i = 0; i < ordersA.length; i++) if (ordersA[i] !== ordersB[i]) return false;
243
+ }
244
+ // If only one side has orders, treat as equal (orders unspecified by user)
245
+ return true;
246
+ }
247
+
248
+ /**
249
+ * Compare individual properties between old and new columns
250
+ */
251
+ function compareColumnProperties(
252
+ oldColumn: any,
253
+ newAttribute: Attribute,
254
+ columnType: string
255
+ ): ColumnPropertyChange[] {
256
+ const changes: ColumnPropertyChange[] = [];
257
+ const t = String(columnType || (newAttribute as any).type || '').toLowerCase();
258
+ const mutableProps = (MUTABLE_PROPERTIES as any)[t] || [];
259
+ const immutableProps = (IMMUTABLE_PROPERTIES as any)[t] || [];
260
+
261
+ const getNewVal = (prop: string) => {
262
+ const na = newAttribute as any;
263
+ if (prop === 'default') return na.xdefault;
264
+ if (prop === 'encrypt') return na.encrypted ?? na.encrypt;
265
+ return na[prop];
266
+ };
267
+ const getOldVal = (prop: string) => {
268
+ if (prop === 'default') return oldColumn?.default ?? oldColumn?.xdefault;
269
+ return oldColumn?.[prop];
270
+ };
271
+
272
+ for (const prop of mutableProps) {
273
+ const oldValue = getOldVal(prop);
274
+ let newValue = getNewVal(prop);
275
+ // Special-case: enum elements empty/missing should not trigger updates
276
+ if (t === 'enum' && prop === 'elements') {
277
+ if (!Array.isArray(newValue) || newValue.length === 0) newValue = oldValue;
278
+ }
279
+ if (Array.isArray(oldValue) && Array.isArray(newValue)) {
280
+ if (oldValue.length !== newValue.length || oldValue.some((v: any, i: number) => v !== newValue[i])) {
281
+ changes.push({ property: prop, oldValue, newValue, requiresRecreate: false });
282
+ }
283
+ } else if (oldValue !== newValue) {
284
+ changes.push({ property: prop, oldValue, newValue, requiresRecreate: false });
285
+ }
286
+ }
287
+
288
+ for (const prop of immutableProps) {
289
+ const oldValue = getOldVal(prop);
290
+ const newValue = getNewVal(prop);
291
+ if (Array.isArray(oldValue) && Array.isArray(newValue)) {
292
+ if (oldValue.length !== newValue.length || oldValue.some((v: any, i: number) => v !== newValue[i])) {
293
+ changes.push({ property: prop, oldValue, newValue, requiresRecreate: true });
294
+ }
295
+ } else if (oldValue !== newValue) {
296
+ changes.push({ property: prop, oldValue, newValue, requiresRecreate: true });
297
+ }
298
+ }
299
+
300
+ // Type change requires recreate (normalize string+elements to enum on old side)
301
+ const oldTypeRaw = String(oldColumn?.type || oldColumn?.columnType || '').toLowerCase();
302
+ const oldHasElements = Array.isArray(oldColumn?.elements) && (oldColumn.elements as any[]).length > 0;
303
+ const oldType = oldTypeRaw === 'string' && oldHasElements ? 'enum' : oldTypeRaw;
304
+ if (oldType && t && oldType !== t && TYPE_CHANGE_REQUIRES_RECREATE.includes(oldType)) {
305
+ changes.push({ property: 'type', oldValue: oldType, newValue: t, requiresRecreate: true });
306
+ }
307
+
308
+ return changes;
309
+ }
310
+
311
+ /**
312
+ * Analyze what changes are needed for a specific column
313
+ */
314
+ function analyzeColumnChanges(
315
+ oldColumn: any,
316
+ newAttribute: Attribute
317
+ ): ColumnChangeAnalysis {
318
+ const columnType = String((newAttribute as any).type || 'string').toLowerCase();
319
+ const columnKey = (newAttribute as any).key;
320
+
321
+
322
+ // Use normalized comparison to reduce false positives then property-wise details
323
+ const normalizedOld = normalizeColumnToComparable(oldColumn);
324
+ const normalizedNew = normalizeAttributeToComparable(newAttribute);
325
+ const hasAnyDiff = !shallowEqual(normalizedOld, normalizedNew);
326
+
327
+ const changes = hasAnyDiff ? compareColumnProperties(oldColumn, newAttribute, columnType) : [];
328
+ const requiresRecreate = changes.some((c) => c.requiresRecreate);
329
+
330
+ const mutableChanges: Record<string, { old: any; new: any }> = {};
331
+ const immutableChanges: Record<string, { old: any; new: any }> = {};
332
+ for (const c of changes) {
333
+ if (c.requiresRecreate) immutableChanges[c.property] = { old: c.oldValue, new: c.newValue };
334
+ else mutableChanges[c.property] = { old: c.oldValue, new: c.newValue };
335
+ }
336
+
337
+ return {
338
+ columnKey,
339
+ columnType,
340
+ hasChanges: changes.length > 0,
341
+ requiresRecreate,
342
+ changes,
343
+ mutableChanges,
344
+ immutableChanges,
345
+ };
346
+ }
347
+
348
+ /**
349
+ * Enhanced version of columns diff with detailed change analysis
350
+ * Order: desired first, then existing (matches internal usage here)
351
+ */
352
+ export function diffColumnsDetailed(
353
+ desiredAttributes: Attribute[],
354
+ existingColumns: any[]
355
+ ): ColumnOperationPlan {
356
+ const byKey = new Map((existingColumns || []).map((col: any) => [col?.key, col] as const));
357
+
358
+ const toCreate: Attribute[] = [];
359
+ const toUpdate: Array<{ attribute: Attribute; changes: ColumnPropertyChange[] }> = [];
360
+ const toRecreate: Array<{ oldAttribute: any; newAttribute: Attribute }> = [];
361
+ const unchanged: string[] = [];
362
+
363
+ for (const attr of desiredAttributes || []) {
364
+ const key = (attr as any)?.key;
365
+ const existing = key ? byKey.get(key) : undefined;
366
+ if (!existing) {
367
+ toCreate.push(attr);
368
+ continue;
369
+ }
370
+ const analysis = analyzeColumnChanges(existing, attr);
371
+ if (!analysis.hasChanges) unchanged.push(analysis.columnKey);
372
+ else if (analysis.requiresRecreate) toRecreate.push({ oldAttribute: existing, newAttribute: attr });
373
+ else toUpdate.push({ attribute: attr, changes: analysis.changes });
374
+ }
375
+
376
+ // Note: we keep toDelete empty for now (conservative behavior)
377
+ return { toCreate, toUpdate, toRecreate, toDelete: [], unchanged };
378
+ }
379
+
380
+ /**
381
+ * Returns true if there is any difference between existing columns and desired attributes
382
+ */
383
+ export function areTableColumnsDiff(existingColumns: any[], desired: Attribute[]): boolean {
384
+ const byKey = new Map<string, any>();
385
+ for (const c of existingColumns || []) {
386
+ if (c?.key) byKey.set(c.key, c);
387
+ }
388
+ for (const attr of desired || []) {
389
+ const desiredNorm = normalizeAttributeToComparable(attr);
390
+ const existing = byKey.get(desiredNorm.key);
391
+ if (!existing) return true;
392
+ const existingNorm = normalizeColumnToComparable(existing);
393
+ if (!shallowEqual(desiredNorm, existingNorm)) return true;
394
+ }
395
+ // Extra columns on remote also constitute a diff
396
+ const desiredKeys = new Set((desired || []).map((a: any) => a.key));
397
+ for (const k of byKey.keys()) if (!desiredKeys.has(k)) return true;
398
+ return false;
399
+ }
400
+
401
+ export function diffTableColumns(existingColumns: any[], desired: Attribute[]): {
402
+ toCreate: Attribute[];
403
+ toUpdate: Attribute[];
404
+ unchanged: string[];
405
+ } {
406
+ // Use detailed plan but return legacy structure for compatibility
407
+ const plan = diffColumnsDetailed(desired, existingColumns);
408
+ const toUpdate: Attribute[] = [
409
+ ...plan.toUpdate.map((u) => u.attribute),
410
+ ...plan.toRecreate.map((r) => r.newAttribute),
411
+ ];
412
+ return { toCreate: plan.toCreate, toUpdate, unchanged: plan.unchanged };
413
+ }
414
+
415
+ /**
416
+ * Execute the column operation plan using the adapter
417
+ */
418
+ export async function executeColumnOperations(
419
+ adapter: any,
420
+ databaseId: string,
421
+ tableId: string,
422
+ plan: ColumnOperationPlan
423
+ ): Promise<{ success: string[]; errors: Array<{ column: string; error: string }> }> {
424
+ if (!databaseId || !tableId) throw new Error('Database ID and Table ID are required for column operations');
425
+ if (!adapter || typeof adapter.createAttribute !== 'function') throw new Error('Valid adapter is required for column operations');
426
+
427
+ const results: { success: string[]; errors: Array<{ column: string; error: string }> } = { success: [], errors: [] };
428
+
429
+ const exec = async (fn: () => Promise<any>, key: string, op: string) => {
430
+ try {
431
+ await fn();
432
+ results.success.push(`${op}: ${key}`);
433
+ } catch (e: any) {
434
+ results.errors.push({ column: key, error: `${op} failed: ${e?.message || String(e)}` });
435
+ }
436
+ };
437
+
438
+ for (const attr of plan.toCreate) {
439
+ const params = mapToCreateAttributeParams(attr as any, { databaseId, tableId });
440
+ await exec(() => adapter.createAttribute(params), (attr as any).key, 'CREATE');
441
+ }
442
+
443
+ for (const { attribute } of plan.toUpdate) {
444
+ const params = mapToUpdateAttributeParams(attribute as any, { databaseId, tableId });
445
+ await exec(() => adapter.updateAttribute(params), (attribute as any).key, 'UPDATE');
446
+ }
447
+
448
+ for (const { oldAttribute, newAttribute } of plan.toRecreate) {
449
+ await exec(() => adapter.deleteAttribute({ databaseId, tableId, key: oldAttribute.key }), oldAttribute.key, 'DELETE (for recreate)');
450
+ // Wait until the attribute is actually removed (or no longer 'deleting') before recreating
451
+ try {
452
+ const start = Date.now();
453
+ const maxWaitMs = 60000; // 60s
454
+ while (Date.now() - start < maxWaitMs) {
455
+ try {
456
+ const tableRes = await adapter.getTable({ databaseId, tableId });
457
+ const cols = (tableRes?.data?.columns || tableRes?.data?.attributes || []) as any[];
458
+ const found = cols.find((c: any) => c.key === oldAttribute.key);
459
+ if (!found) break; // fully removed
460
+ if (found.status && found.status !== 'deleting') break; // no longer deleting (failed/stuck) -> stop waiting
461
+ } catch {}
462
+ await new Promise((r) => setTimeout(r, 1500));
463
+ }
464
+ } catch {}
465
+ const params = mapToCreateAttributeParams(newAttribute as any, { databaseId, tableId });
466
+ await exec(() => adapter.createAttribute(params), (newAttribute as any).key, 'CREATE (after recreate)');
467
+ }
468
+
469
+ return results;
470
+ }
471
+
472
+ /**
473
+ * Integration function for methods.ts - processes columns using enhanced logic
474
+ */
475
+ export async function processTableColumns(
476
+ adapter: any,
477
+ databaseId: string,
478
+ tableId: string,
479
+ desiredAttributes: Attribute[],
480
+ existingColumns: any[] = []
481
+ ): Promise<{
482
+ totalProcessed: number;
483
+ success: string[];
484
+ errors: Array<{ column: string; error: string }>;
485
+ summary: { created: number; updated: number; recreated: number; unchanged: number };
486
+ }> {
487
+ if (!existingColumns || existingColumns.length === 0) {
488
+ const tableInfo = await adapter.getTable({ databaseId, tableId });
489
+ existingColumns = (tableInfo?.data?.columns || tableInfo?.data?.attributes || []) as any[];
490
+ }
491
+
492
+ const plan = diffColumnsDetailed(desiredAttributes, existingColumns);
493
+ const results = await executeColumnOperations(adapter, databaseId, tableId, plan);
494
+
495
+ return {
496
+ totalProcessed: plan.toCreate.length + plan.toUpdate.length + plan.toRecreate.length,
497
+ success: results.success,
498
+ errors: results.errors,
499
+ summary: {
500
+ created: plan.toCreate.length,
501
+ updated: plan.toUpdate.length,
502
+ recreated: plan.toRecreate.length,
503
+ unchanged: plan.unchanged.length,
504
+ },
505
+ };
506
+ }