@carbonorm/carbonnode 3.8.4 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,65 @@
1
1
  // Alias a table name with a given alias
2
2
  import {C6C} from "../C6Constants";
3
3
 
4
+ type DerivedTableSpec = Record<string, any> & {
5
+ [C6C.SUBSELECT]?: Record<string, any>;
6
+ [C6C.AS]?: string;
7
+ };
8
+
9
+ const DERIVED_TABLE_PREFIX = '__c6DerivedTable__';
10
+ const DERIVED_ID_SYMBOL = Symbol('c6DerivedTableId');
11
+
12
+ const derivedTableLookup = new Map<string, DerivedTableSpec>();
13
+ const derivedTableReverseLookup = new WeakMap<DerivedTableSpec, string>();
14
+ let derivedTableCounter = 0;
15
+
16
+ export const isDerivedTableKey = (key: string): boolean =>
17
+ typeof key === 'string' && key.startsWith(DERIVED_TABLE_PREFIX);
18
+
19
+ export const resolveDerivedTable = (key: string): DerivedTableSpec | undefined =>
20
+ derivedTableLookup.get(key);
21
+
22
+ export const derivedTable = <T extends DerivedTableSpec>(spec: T): T => {
23
+ if (!spec || typeof spec !== 'object') {
24
+ throw new Error('Derived table definition must be an object.');
25
+ }
26
+
27
+ const aliasRaw = spec[C6C.AS];
28
+ if (typeof aliasRaw !== 'string' || aliasRaw.trim() === '') {
29
+ throw new Error('Derived tables require a non-empty alias via C6C.AS.');
30
+ }
31
+
32
+ if (!spec[C6C.SUBSELECT] || typeof spec[C6C.SUBSELECT] !== 'object') {
33
+ throw new Error('Derived tables require a nested SELECT payload under C6C.SUBSELECT.');
34
+ }
35
+
36
+ let id = derivedTableReverseLookup.get(spec);
37
+
38
+ if (!id) {
39
+ id = `${DERIVED_TABLE_PREFIX}${++derivedTableCounter}`;
40
+ derivedTableReverseLookup.set(spec, id);
41
+ derivedTableLookup.set(id, spec);
42
+ Object.defineProperty(spec, DERIVED_ID_SYMBOL, {
43
+ value: id,
44
+ configurable: false,
45
+ enumerable: false,
46
+ writable: false
47
+ });
48
+ }
49
+
50
+ const alias = aliasRaw.trim();
51
+ derivedTableLookup.set(id!, spec);
52
+
53
+ Object.defineProperty(spec, 'toString', {
54
+ value: () => `${id} ${alias}`,
55
+ configurable: true,
56
+ enumerable: false,
57
+ writable: true
58
+ });
59
+
60
+ return spec;
61
+ };
62
+
4
63
  export const A = (tableName: string, alias: string): string =>
5
64
  `${tableName} ${alias}`;
6
65