@tanstack/db 0.0.14 → 0.0.15

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 (198) hide show
  1. package/dist/cjs/collection.cjs +117 -104
  2. package/dist/cjs/collection.cjs.map +1 -1
  3. package/dist/cjs/collection.d.cts +18 -21
  4. package/dist/cjs/index.cjs +35 -13
  5. package/dist/cjs/index.cjs.map +1 -1
  6. package/dist/cjs/index.d.cts +0 -1
  7. package/dist/cjs/query/builder/functions.cjs +107 -0
  8. package/dist/cjs/query/builder/functions.cjs.map +1 -0
  9. package/dist/cjs/query/builder/functions.d.cts +38 -0
  10. package/dist/cjs/query/builder/index.cjs +499 -0
  11. package/dist/cjs/query/builder/index.cjs.map +1 -0
  12. package/dist/cjs/query/builder/index.d.cts +324 -0
  13. package/dist/cjs/query/builder/ref-proxy.cjs +96 -0
  14. package/dist/cjs/query/builder/ref-proxy.cjs.map +1 -0
  15. package/dist/cjs/query/builder/ref-proxy.d.cts +28 -0
  16. package/dist/cjs/query/builder/types.d.cts +80 -0
  17. package/dist/cjs/query/compiler/evaluators.cjs +261 -0
  18. package/dist/cjs/query/compiler/evaluators.cjs.map +1 -0
  19. package/dist/cjs/query/compiler/evaluators.d.cts +11 -0
  20. package/dist/cjs/query/compiler/group-by.cjs +271 -0
  21. package/dist/cjs/query/compiler/group-by.cjs.map +1 -0
  22. package/dist/cjs/query/compiler/group-by.d.cts +7 -0
  23. package/dist/cjs/query/compiler/index.cjs +181 -0
  24. package/dist/cjs/query/compiler/index.cjs.map +1 -0
  25. package/dist/cjs/query/compiler/index.d.cts +15 -0
  26. package/dist/cjs/query/compiler/joins.cjs +116 -0
  27. package/dist/cjs/query/compiler/joins.cjs.map +1 -0
  28. package/dist/cjs/query/compiler/joins.d.cts +11 -0
  29. package/dist/cjs/query/compiler/order-by.cjs +89 -0
  30. package/dist/cjs/query/compiler/order-by.cjs.map +1 -0
  31. package/dist/cjs/query/compiler/order-by.d.cts +9 -0
  32. package/dist/cjs/query/compiler/select.cjs +57 -0
  33. package/dist/cjs/query/compiler/select.cjs.map +1 -0
  34. package/dist/cjs/query/compiler/select.d.cts +15 -0
  35. package/dist/cjs/query/index.d.cts +6 -5
  36. package/dist/cjs/query/ir.cjs +57 -0
  37. package/dist/cjs/query/ir.cjs.map +1 -0
  38. package/dist/cjs/query/ir.d.cts +81 -0
  39. package/dist/cjs/query/live-query-collection.cjs +224 -0
  40. package/dist/cjs/query/live-query-collection.cjs.map +1 -0
  41. package/dist/cjs/query/live-query-collection.d.cts +124 -0
  42. package/dist/cjs/transactions.cjs +20 -13
  43. package/dist/cjs/transactions.cjs.map +1 -1
  44. package/dist/cjs/transactions.d.cts +10 -1
  45. package/dist/cjs/types.d.cts +13 -0
  46. package/dist/esm/collection.d.ts +18 -21
  47. package/dist/esm/collection.js +118 -105
  48. package/dist/esm/collection.js.map +1 -1
  49. package/dist/esm/index.d.ts +0 -1
  50. package/dist/esm/index.js +34 -12
  51. package/dist/esm/index.js.map +1 -1
  52. package/dist/esm/query/builder/functions.d.ts +38 -0
  53. package/dist/esm/query/builder/functions.js +107 -0
  54. package/dist/esm/query/builder/functions.js.map +1 -0
  55. package/dist/esm/query/builder/index.d.ts +324 -0
  56. package/dist/esm/query/builder/index.js +499 -0
  57. package/dist/esm/query/builder/index.js.map +1 -0
  58. package/dist/esm/query/builder/ref-proxy.d.ts +28 -0
  59. package/dist/esm/query/builder/ref-proxy.js +96 -0
  60. package/dist/esm/query/builder/ref-proxy.js.map +1 -0
  61. package/dist/esm/query/builder/types.d.ts +80 -0
  62. package/dist/esm/query/compiler/evaluators.d.ts +11 -0
  63. package/dist/esm/query/compiler/evaluators.js +261 -0
  64. package/dist/esm/query/compiler/evaluators.js.map +1 -0
  65. package/dist/esm/query/compiler/group-by.d.ts +7 -0
  66. package/dist/esm/query/compiler/group-by.js +271 -0
  67. package/dist/esm/query/compiler/group-by.js.map +1 -0
  68. package/dist/esm/query/compiler/index.d.ts +15 -0
  69. package/dist/esm/query/compiler/index.js +181 -0
  70. package/dist/esm/query/compiler/index.js.map +1 -0
  71. package/dist/esm/query/compiler/joins.d.ts +11 -0
  72. package/dist/esm/query/compiler/joins.js +116 -0
  73. package/dist/esm/query/compiler/joins.js.map +1 -0
  74. package/dist/esm/query/compiler/order-by.d.ts +9 -0
  75. package/dist/esm/query/compiler/order-by.js +89 -0
  76. package/dist/esm/query/compiler/order-by.js.map +1 -0
  77. package/dist/esm/query/compiler/select.d.ts +15 -0
  78. package/dist/esm/query/compiler/select.js +57 -0
  79. package/dist/esm/query/compiler/select.js.map +1 -0
  80. package/dist/esm/query/index.d.ts +6 -5
  81. package/dist/esm/query/ir.d.ts +81 -0
  82. package/dist/esm/query/ir.js +57 -0
  83. package/dist/esm/query/ir.js.map +1 -0
  84. package/dist/esm/query/live-query-collection.d.ts +124 -0
  85. package/dist/esm/query/live-query-collection.js +224 -0
  86. package/dist/esm/query/live-query-collection.js.map +1 -0
  87. package/dist/esm/transactions.d.ts +10 -1
  88. package/dist/esm/transactions.js +20 -13
  89. package/dist/esm/transactions.js.map +1 -1
  90. package/dist/esm/types.d.ts +13 -0
  91. package/package.json +3 -4
  92. package/src/collection.ts +152 -129
  93. package/src/index.ts +0 -1
  94. package/src/query/builder/functions.ts +267 -0
  95. package/src/query/builder/index.ts +648 -0
  96. package/src/query/builder/ref-proxy.ts +156 -0
  97. package/src/query/builder/types.ts +278 -0
  98. package/src/query/compiler/evaluators.ts +315 -0
  99. package/src/query/compiler/group-by.ts +428 -0
  100. package/src/query/compiler/index.ts +276 -0
  101. package/src/query/compiler/joins.ts +228 -0
  102. package/src/query/compiler/order-by.ts +139 -0
  103. package/src/query/compiler/select.ts +173 -0
  104. package/src/query/index.ts +64 -5
  105. package/src/query/ir.ts +128 -0
  106. package/src/query/live-query-collection.ts +509 -0
  107. package/src/transactions.ts +27 -16
  108. package/src/types.ts +15 -0
  109. package/dist/cjs/query/compiled-query.cjs +0 -160
  110. package/dist/cjs/query/compiled-query.cjs.map +0 -1
  111. package/dist/cjs/query/compiled-query.d.cts +0 -20
  112. package/dist/cjs/query/evaluators.cjs +0 -161
  113. package/dist/cjs/query/evaluators.cjs.map +0 -1
  114. package/dist/cjs/query/evaluators.d.cts +0 -14
  115. package/dist/cjs/query/extractors.cjs +0 -122
  116. package/dist/cjs/query/extractors.cjs.map +0 -1
  117. package/dist/cjs/query/extractors.d.cts +0 -22
  118. package/dist/cjs/query/functions.cjs +0 -152
  119. package/dist/cjs/query/functions.cjs.map +0 -1
  120. package/dist/cjs/query/functions.d.cts +0 -21
  121. package/dist/cjs/query/group-by.cjs +0 -88
  122. package/dist/cjs/query/group-by.cjs.map +0 -1
  123. package/dist/cjs/query/group-by.d.cts +0 -40
  124. package/dist/cjs/query/joins.cjs +0 -141
  125. package/dist/cjs/query/joins.cjs.map +0 -1
  126. package/dist/cjs/query/joins.d.cts +0 -14
  127. package/dist/cjs/query/order-by.cjs +0 -185
  128. package/dist/cjs/query/order-by.cjs.map +0 -1
  129. package/dist/cjs/query/order-by.d.cts +0 -3
  130. package/dist/cjs/query/pipeline-compiler.cjs +0 -89
  131. package/dist/cjs/query/pipeline-compiler.cjs.map +0 -1
  132. package/dist/cjs/query/pipeline-compiler.d.cts +0 -10
  133. package/dist/cjs/query/query-builder.cjs +0 -307
  134. package/dist/cjs/query/query-builder.cjs.map +0 -1
  135. package/dist/cjs/query/query-builder.d.cts +0 -225
  136. package/dist/cjs/query/schema.d.cts +0 -100
  137. package/dist/cjs/query/select.cjs +0 -130
  138. package/dist/cjs/query/select.cjs.map +0 -1
  139. package/dist/cjs/query/select.d.cts +0 -3
  140. package/dist/cjs/query/types.d.cts +0 -189
  141. package/dist/cjs/query/utils.cjs +0 -154
  142. package/dist/cjs/query/utils.cjs.map +0 -1
  143. package/dist/cjs/query/utils.d.cts +0 -37
  144. package/dist/cjs/utils.cjs +0 -17
  145. package/dist/cjs/utils.cjs.map +0 -1
  146. package/dist/cjs/utils.d.cts +0 -3
  147. package/dist/esm/query/compiled-query.d.ts +0 -20
  148. package/dist/esm/query/compiled-query.js +0 -160
  149. package/dist/esm/query/compiled-query.js.map +0 -1
  150. package/dist/esm/query/evaluators.d.ts +0 -14
  151. package/dist/esm/query/evaluators.js +0 -161
  152. package/dist/esm/query/evaluators.js.map +0 -1
  153. package/dist/esm/query/extractors.d.ts +0 -22
  154. package/dist/esm/query/extractors.js +0 -122
  155. package/dist/esm/query/extractors.js.map +0 -1
  156. package/dist/esm/query/functions.d.ts +0 -21
  157. package/dist/esm/query/functions.js +0 -152
  158. package/dist/esm/query/functions.js.map +0 -1
  159. package/dist/esm/query/group-by.d.ts +0 -40
  160. package/dist/esm/query/group-by.js +0 -88
  161. package/dist/esm/query/group-by.js.map +0 -1
  162. package/dist/esm/query/joins.d.ts +0 -14
  163. package/dist/esm/query/joins.js +0 -141
  164. package/dist/esm/query/joins.js.map +0 -1
  165. package/dist/esm/query/order-by.d.ts +0 -3
  166. package/dist/esm/query/order-by.js +0 -185
  167. package/dist/esm/query/order-by.js.map +0 -1
  168. package/dist/esm/query/pipeline-compiler.d.ts +0 -10
  169. package/dist/esm/query/pipeline-compiler.js +0 -89
  170. package/dist/esm/query/pipeline-compiler.js.map +0 -1
  171. package/dist/esm/query/query-builder.d.ts +0 -225
  172. package/dist/esm/query/query-builder.js +0 -307
  173. package/dist/esm/query/query-builder.js.map +0 -1
  174. package/dist/esm/query/schema.d.ts +0 -100
  175. package/dist/esm/query/select.d.ts +0 -3
  176. package/dist/esm/query/select.js +0 -130
  177. package/dist/esm/query/select.js.map +0 -1
  178. package/dist/esm/query/types.d.ts +0 -189
  179. package/dist/esm/query/utils.d.ts +0 -37
  180. package/dist/esm/query/utils.js +0 -154
  181. package/dist/esm/query/utils.js.map +0 -1
  182. package/dist/esm/utils.d.ts +0 -3
  183. package/dist/esm/utils.js +0 -17
  184. package/dist/esm/utils.js.map +0 -1
  185. package/src/query/compiled-query.ts +0 -234
  186. package/src/query/evaluators.ts +0 -250
  187. package/src/query/extractors.ts +0 -214
  188. package/src/query/functions.ts +0 -297
  189. package/src/query/group-by.ts +0 -139
  190. package/src/query/joins.ts +0 -260
  191. package/src/query/order-by.ts +0 -264
  192. package/src/query/pipeline-compiler.ts +0 -149
  193. package/src/query/query-builder.ts +0 -902
  194. package/src/query/schema.ts +0 -268
  195. package/src/query/select.ts +0 -208
  196. package/src/query/types.ts +0 -418
  197. package/src/query/utils.ts +0 -245
  198. package/src/utils.ts +0 -15
@@ -1,22 +0,0 @@
1
- import { ConditionOperand } from './schema.js';
2
- /**
3
- * Extracts a value from a nested row structure
4
- * @param namespacedRow The nested row structure
5
- * @param columnRef The column reference (may include table.column format)
6
- * @param mainTableAlias The main table alias to check first for columns without table reference
7
- * @param joinedTableAlias The joined table alias to check second for columns without table reference
8
- * @returns The extracted value or undefined if not found
9
- */
10
- export declare function extractValueFromNamespacedRow(namespacedRow: Record<string, unknown>, columnRef: string, mainTableAlias?: string, joinedTableAlias?: string): unknown;
11
- /**
12
- * Evaluates an operand against a nested row structure
13
- */
14
- export declare function evaluateOperandOnNamespacedRow(namespacedRow: Record<string, unknown>, operand: ConditionOperand, mainTableAlias?: string, joinedTableAlias?: string): unknown;
15
- /**
16
- * Extracts a join key value from a row based on the operand
17
- * @param row The data row (not nested)
18
- * @param operand The operand to extract the key from
19
- * @param defaultTableAlias The default table alias
20
- * @returns The extracted key value
21
- */
22
- export declare function extractJoinKey<T extends Record<string, unknown>>(row: T, operand: ConditionOperand, defaultTableAlias?: string): unknown;
@@ -1,152 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- function upperFunction(arg) {
4
- if (typeof arg !== `string`) {
5
- throw new Error(`UPPER function expects a string argument`);
6
- }
7
- return arg.toUpperCase();
8
- }
9
- function lowerFunction(arg) {
10
- if (typeof arg !== `string`) {
11
- throw new Error(`LOWER function expects a string argument`);
12
- }
13
- return arg.toLowerCase();
14
- }
15
- function lengthFunction(arg) {
16
- if (typeof arg === `string` || Array.isArray(arg)) {
17
- return arg.length;
18
- }
19
- throw new Error(`LENGTH function expects a string or array argument`);
20
- }
21
- function concatFunction(arg) {
22
- if (!Array.isArray(arg)) {
23
- throw new Error(`CONCAT function expects an array of string arguments`);
24
- }
25
- if (arg.length === 0) {
26
- return ``;
27
- }
28
- for (let i = 0; i < arg.length; i++) {
29
- if (arg[i] !== null && arg[i] !== void 0 && typeof arg[i] !== `string`) {
30
- throw new Error(
31
- `CONCAT function expects all arguments to be strings, but argument at position ${i} is ${typeof arg[i]}`
32
- );
33
- }
34
- }
35
- return arg.map((str) => str === null || str === void 0 ? `` : str).join(``);
36
- }
37
- function coalesceFunction(arg) {
38
- if (!Array.isArray(arg)) {
39
- throw new Error(`COALESCE function expects an array of arguments`);
40
- }
41
- if (arg.length === 0) {
42
- return null;
43
- }
44
- for (const value of arg) {
45
- if (value !== null && value !== void 0) {
46
- return value;
47
- }
48
- }
49
- return null;
50
- }
51
- function dateFunction(arg) {
52
- if (arg instanceof Date) {
53
- return arg;
54
- }
55
- if (arg === null || arg === void 0) {
56
- return null;
57
- }
58
- if (typeof arg === `string` || typeof arg === `number`) {
59
- const date = new Date(arg);
60
- if (isNaN(date.getTime())) {
61
- throw new Error(`DATE function could not parse "${arg}" as a valid date`);
62
- }
63
- return date;
64
- }
65
- throw new Error(`DATE function expects a string, number, or Date argument`);
66
- }
67
- function jsonExtractFunction(arg) {
68
- if (!Array.isArray(arg) || arg.length < 1) {
69
- throw new Error(
70
- `JSON_EXTRACT function expects an array with at least one element [jsonInput, ...pathElements]`
71
- );
72
- }
73
- const [jsonInput, ...pathElements] = arg;
74
- if (jsonInput === null || jsonInput === void 0) {
75
- return null;
76
- }
77
- let jsonData;
78
- if (typeof jsonInput === `string`) {
79
- try {
80
- jsonData = JSON.parse(jsonInput);
81
- } catch (error) {
82
- throw new Error(
83
- `JSON_EXTRACT function could not parse JSON string: ${error instanceof Error ? error.message : String(error)}`
84
- );
85
- }
86
- } else if (typeof jsonInput === `object`) {
87
- jsonData = jsonInput;
88
- } else {
89
- throw new Error(
90
- `JSON_EXTRACT function expects a JSON string or object as the first argument`
91
- );
92
- }
93
- if (pathElements.length === 0) {
94
- return jsonData;
95
- }
96
- let current = jsonData;
97
- for (let i = 0; i < pathElements.length; i++) {
98
- const pathElement = pathElements[i];
99
- if (typeof pathElement !== `string`) {
100
- throw new Error(
101
- `JSON_EXTRACT function expects path elements to be strings, but element at position ${i + 1} is ${typeof pathElement}`
102
- );
103
- }
104
- if (current === null || current === void 0 || typeof current !== `object`) {
105
- return null;
106
- }
107
- current = current[pathElement];
108
- }
109
- return current === void 0 ? null : current;
110
- }
111
- function orderIndexFunction(arg) {
112
- if (arg !== `numeric` && arg !== `fractional` && arg !== true && arg !== `default`) {
113
- throw new Error(
114
- `ORDER_INDEX function expects "numeric", "fractional", "default", or true as argument`
115
- );
116
- }
117
- return null;
118
- }
119
- const functionImplementations = {
120
- // Map function names to their implementation functions
121
- DATE: dateFunction,
122
- JSON_EXTRACT: jsonExtractFunction,
123
- JSON_EXTRACT_PATH: jsonExtractFunction,
124
- // Alias for JSON_EXTRACT
125
- UPPER: upperFunction,
126
- LOWER: lowerFunction,
127
- COALESCE: coalesceFunction,
128
- CONCAT: concatFunction,
129
- LENGTH: lengthFunction,
130
- ORDER_INDEX: orderIndexFunction
131
- };
132
- function evaluateFunction(functionName, arg) {
133
- const implementation = functionImplementations[functionName];
134
- if (!implementation) {
135
- throw new Error(`Unknown function: ${functionName}`);
136
- }
137
- return implementation(arg);
138
- }
139
- function isFunctionCall(obj) {
140
- if (!obj || typeof obj !== `object`) {
141
- return false;
142
- }
143
- const keys = Object.keys(obj);
144
- if (keys.length !== 1) {
145
- return false;
146
- }
147
- const functionName = keys[0];
148
- return Object.keys(functionImplementations).includes(functionName);
149
- }
150
- exports.evaluateFunction = evaluateFunction;
151
- exports.isFunctionCall = isFunctionCall;
152
- //# sourceMappingURL=functions.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"functions.cjs","sources":["../../../src/query/functions.ts"],"sourcesContent":["import type { AllowedFunctionName } from \"./schema.js\"\n\n/**\n * Type for function implementations\n */\ntype FunctionImplementation = (arg: unknown) => unknown\n\n/**\n * Converts a string to uppercase\n */\nfunction upperFunction(arg: unknown): string {\n if (typeof arg !== `string`) {\n throw new Error(`UPPER function expects a string argument`)\n }\n return arg.toUpperCase()\n}\n\n/**\n * Converts a string to lowercase\n */\nfunction lowerFunction(arg: unknown): string {\n if (typeof arg !== `string`) {\n throw new Error(`LOWER function expects a string argument`)\n }\n return arg.toLowerCase()\n}\n\n/**\n * Returns the length of a string or array\n */\nfunction lengthFunction(arg: unknown): number {\n if (typeof arg === `string` || Array.isArray(arg)) {\n return arg.length\n }\n\n throw new Error(`LENGTH function expects a string or array argument`)\n}\n\n/**\n * Concatenates multiple strings\n */\nfunction concatFunction(arg: unknown): string {\n if (!Array.isArray(arg)) {\n throw new Error(`CONCAT function expects an array of string arguments`)\n }\n\n if (arg.length === 0) {\n return ``\n }\n\n // Check that all arguments are strings\n for (let i = 0; i < arg.length; i++) {\n if (arg[i] !== null && arg[i] !== undefined && typeof arg[i] !== `string`) {\n throw new Error(\n `CONCAT function expects all arguments to be strings, but argument at position ${i} is ${typeof arg[i]}`\n )\n }\n }\n\n // Concatenate strings, treating null and undefined as empty strings\n return arg\n .map((str) => (str === null || str === undefined ? `` : str))\n .join(``)\n}\n\n/**\n * Returns the first non-null, non-undefined value from an array\n */\nfunction coalesceFunction(arg: unknown): unknown {\n if (!Array.isArray(arg)) {\n throw new Error(`COALESCE function expects an array of arguments`)\n }\n\n if (arg.length === 0) {\n return null\n }\n\n // Return the first non-null, non-undefined value\n for (const value of arg) {\n if (value !== null && value !== undefined) {\n return value\n }\n }\n\n // If all values were null or undefined, return null\n return null\n}\n\n/**\n * Creates or converts a value to a Date object\n */\nfunction dateFunction(arg: unknown): Date | null {\n // If the argument is already a Date, return it\n if (arg instanceof Date) {\n return arg\n }\n\n // If the argument is null or undefined, return null\n if (arg === null || arg === undefined) {\n return null\n }\n\n // Handle string and number conversions\n if (typeof arg === `string` || typeof arg === `number`) {\n const date = new Date(arg)\n\n // Check if the date is valid\n if (isNaN(date.getTime())) {\n throw new Error(`DATE function could not parse \"${arg}\" as a valid date`)\n }\n\n return date\n }\n\n throw new Error(`DATE function expects a string, number, or Date argument`)\n}\n\n/**\n * Extracts a value from a JSON string or object using a path.\n * Similar to PostgreSQL's json_extract_path function.\n *\n * Usage: JSON_EXTRACT([jsonInput, 'path', 'to', 'property'])\n * Example: JSON_EXTRACT(['{\"user\": {\"name\": \"John\"}}', 'user', 'name']) returns \"John\"\n */\nfunction jsonExtractFunction(arg: unknown): unknown {\n if (!Array.isArray(arg) || arg.length < 1) {\n throw new Error(\n `JSON_EXTRACT function expects an array with at least one element [jsonInput, ...pathElements]`\n )\n }\n\n const [jsonInput, ...pathElements] = arg\n\n // Handle null or undefined input\n if (jsonInput === null || jsonInput === undefined) {\n return null\n }\n\n // Parse JSON if it's a string\n let jsonData: any\n\n if (typeof jsonInput === `string`) {\n try {\n jsonData = JSON.parse(jsonInput)\n } catch (error) {\n throw new Error(\n `JSON_EXTRACT function could not parse JSON string: ${error instanceof Error ? error.message : String(error)}`\n )\n }\n } else if (typeof jsonInput === `object`) {\n // If already an object, use it directly\n jsonData = jsonInput\n } else {\n throw new Error(\n `JSON_EXTRACT function expects a JSON string or object as the first argument`\n )\n }\n\n // If no path elements, return the parsed JSON\n if (pathElements.length === 0) {\n return jsonData\n }\n\n // Navigate through the path elements\n let current = jsonData\n\n for (let i = 0; i < pathElements.length; i++) {\n const pathElement = pathElements[i]\n\n // Path elements should be strings\n if (typeof pathElement !== `string`) {\n throw new Error(\n `JSON_EXTRACT function expects path elements to be strings, but element at position ${i + 1} is ${typeof pathElement}`\n )\n }\n\n // If current node is null or undefined, or not an object, we can't navigate further\n if (\n current === null ||\n current === undefined ||\n typeof current !== `object`\n ) {\n return null\n }\n\n // Access property\n current = current[pathElement]\n }\n\n // Return null instead of undefined for consistency\n return current === undefined ? null : current\n}\n\n/**\n * Placeholder function for ORDER_INDEX\n * This function doesn't do anything when called directly, as the actual index\n * is provided by the orderBy operator during query execution.\n * The argument can be 'numeric', 'fractional', or any truthy value (defaults to 'numeric')\n */\nfunction orderIndexFunction(arg: unknown): null {\n // This is just a placeholder - the actual index is provided by the orderBy operator\n // The function validates that the argument is one of the expected values\n if (\n arg !== `numeric` &&\n arg !== `fractional` &&\n arg !== true &&\n arg !== `default`\n ) {\n throw new Error(\n `ORDER_INDEX function expects \"numeric\", \"fractional\", \"default\", or true as argument`\n )\n }\n return null\n}\n\n/**\n * Map of function names to their implementations\n */\nconst functionImplementations: Record<\n AllowedFunctionName,\n FunctionImplementation\n> = {\n // Map function names to their implementation functions\n DATE: dateFunction,\n JSON_EXTRACT: jsonExtractFunction,\n JSON_EXTRACT_PATH: jsonExtractFunction, // Alias for JSON_EXTRACT\n UPPER: upperFunction,\n LOWER: lowerFunction,\n COALESCE: coalesceFunction,\n CONCAT: concatFunction,\n LENGTH: lengthFunction,\n ORDER_INDEX: orderIndexFunction,\n}\n\n/**\n * Evaluates a function call with the given name and arguments\n * @param functionName The name of the function to evaluate\n * @param arg The arguments to pass to the function\n * @returns The result of the function call\n */\nexport function evaluateFunction(\n functionName: AllowedFunctionName,\n arg: unknown\n): unknown {\n const implementation = functionImplementations[functionName] as\n | FunctionImplementation\n | undefined // Double check that the implementation is defined\n\n if (!implementation) {\n throw new Error(`Unknown function: ${functionName}`)\n }\n return implementation(arg)\n}\n\n/**\n * Determines if an object is a function call\n * @param obj The object to check\n * @returns True if the object is a function call, false otherwise\n */\nexport function isFunctionCall(obj: unknown): boolean {\n if (!obj || typeof obj !== `object`) {\n return false\n }\n\n const keys = Object.keys(obj)\n if (keys.length !== 1) {\n return false\n }\n\n const functionName = keys[0] as string\n\n // Check if the key is one of the allowed function names\n return Object.keys(functionImplementations).includes(functionName)\n}\n\n/**\n * Extracts the function name and argument from a function call object.\n */\nexport function extractFunctionCall(obj: Record<string, unknown>): {\n functionName: AllowedFunctionName\n argument: unknown\n} {\n const keys = Object.keys(obj)\n if (keys.length !== 1) {\n throw new Error(`Invalid function call: object must have exactly one key`)\n }\n\n const functionName = keys[0] as AllowedFunctionName\n if (!Object.keys(functionImplementations).includes(functionName)) {\n throw new Error(`Invalid function name: ${functionName}`)\n }\n\n return {\n functionName,\n argument: obj[functionName],\n }\n}\n"],"names":[],"mappings":";;AAUA,SAAS,cAAc,KAAsB;AACvC,MAAA,OAAO,QAAQ,UAAU;AACrB,UAAA,IAAI,MAAM,0CAA0C;AAAA,EAAA;AAE5D,SAAO,IAAI,YAAY;AACzB;AAKA,SAAS,cAAc,KAAsB;AACvC,MAAA,OAAO,QAAQ,UAAU;AACrB,UAAA,IAAI,MAAM,0CAA0C;AAAA,EAAA;AAE5D,SAAO,IAAI,YAAY;AACzB;AAKA,SAAS,eAAe,KAAsB;AAC5C,MAAI,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,GAAG;AACjD,WAAO,IAAI;AAAA,EAAA;AAGP,QAAA,IAAI,MAAM,oDAAoD;AACtE;AAKA,SAAS,eAAe,KAAsB;AAC5C,MAAI,CAAC,MAAM,QAAQ,GAAG,GAAG;AACjB,UAAA,IAAI,MAAM,sDAAsD;AAAA,EAAA;AAGpE,MAAA,IAAI,WAAW,GAAG;AACb,WAAA;AAAA,EAAA;AAIT,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,QAAI,IAAI,CAAC,MAAM,QAAQ,IAAI,CAAC,MAAM,UAAa,OAAO,IAAI,CAAC,MAAM,UAAU;AACzE,YAAM,IAAI;AAAA,QACR,iFAAiF,CAAC,OAAO,OAAO,IAAI,CAAC,CAAC;AAAA,MACxG;AAAA,IAAA;AAAA,EACF;AAIF,SAAO,IACJ,IAAI,CAAC,QAAS,QAAQ,QAAQ,QAAQ,SAAY,KAAK,GAAI,EAC3D,KAAK,EAAE;AACZ;AAKA,SAAS,iBAAiB,K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@@ -1,21 +0,0 @@
1
- import { AllowedFunctionName } from './schema.js';
2
- /**
3
- * Evaluates a function call with the given name and arguments
4
- * @param functionName The name of the function to evaluate
5
- * @param arg The arguments to pass to the function
6
- * @returns The result of the function call
7
- */
8
- export declare function evaluateFunction(functionName: AllowedFunctionName, arg: unknown): unknown;
9
- /**
10
- * Determines if an object is a function call
11
- * @param obj The object to check
12
- * @returns True if the object is a function call, false otherwise
13
- */
14
- export declare function isFunctionCall(obj: unknown): boolean;
15
- /**
16
- * Extracts the function name and argument from a function call object.
17
- */
18
- export declare function extractFunctionCall(obj: Record<string, unknown>): {
19
- functionName: AllowedFunctionName;
20
- argument: unknown;
21
- };
@@ -1,88 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const d2mini = require("@electric-sql/d2mini");
4
- const extractors = require("./extractors.cjs");
5
- const utils = require("./utils.cjs");
6
- const { sum, count, avg, min, max, median, mode } = d2mini.groupByOperators;
7
- function processGroupBy(pipeline, query, mainTableAlias) {
8
- const groupByColumns = Array.isArray(query.groupBy) ? query.groupBy : [query.groupBy];
9
- const keyExtractor = ([_oldKey, namespacedRow]) => {
10
- const key = {};
11
- for (const column of groupByColumns) {
12
- if (typeof column === `string` && column.startsWith(`@`)) {
13
- const columnRef = column.substring(1);
14
- const columnName = columnRef.includes(`.`) ? columnRef.split(`.`)[1] : columnRef;
15
- key[columnName] = extractors.extractValueFromNamespacedRow(
16
- namespacedRow,
17
- columnRef,
18
- mainTableAlias
19
- );
20
- }
21
- }
22
- return key;
23
- };
24
- const aggregates = {};
25
- if (!query.select) {
26
- throw new Error(`SELECT clause is required for GROUP BY`);
27
- }
28
- for (const item of query.select) {
29
- if (typeof item === `object`) {
30
- for (const [alias, expr] of Object.entries(item)) {
31
- if (typeof expr === `object` && utils.isAggregateFunctionCall(expr)) {
32
- const functionName = Object.keys(expr)[0];
33
- const columnRef = expr[functionName];
34
- aggregates[alias] = getAggregateFunction(
35
- functionName,
36
- columnRef,
37
- mainTableAlias
38
- );
39
- }
40
- }
41
- }
42
- }
43
- if (Object.keys(aggregates).length > 0) {
44
- pipeline = pipeline.pipe(d2mini.groupBy(keyExtractor, aggregates));
45
- }
46
- return pipeline;
47
- }
48
- function getAggregateFunction(functionName, columnRef, mainTableAlias) {
49
- const valueExtractor = ([_oldKey, namespacedRow]) => {
50
- let value;
51
- if (typeof columnRef === `string` && columnRef.startsWith(`@`)) {
52
- value = extractors.extractValueFromNamespacedRow(
53
- namespacedRow,
54
- columnRef.substring(1),
55
- mainTableAlias
56
- );
57
- } else {
58
- value = extractors.evaluateOperandOnNamespacedRow(
59
- namespacedRow,
60
- columnRef,
61
- mainTableAlias
62
- );
63
- }
64
- return typeof value === `number` ? value : 0;
65
- };
66
- switch (functionName.toUpperCase()) {
67
- case `SUM`:
68
- return sum(valueExtractor);
69
- case `COUNT`:
70
- return count();
71
- // count() doesn't need a value extractor
72
- case `AVG`:
73
- return avg(valueExtractor);
74
- case `MIN`:
75
- return min(valueExtractor);
76
- case `MAX`:
77
- return max(valueExtractor);
78
- case `MEDIAN`:
79
- return median(valueExtractor);
80
- case `MODE`:
81
- return mode(valueExtractor);
82
- default:
83
- throw new Error(`Unsupported aggregate function: ${functionName}`);
84
- }
85
- }
86
- exports.getAggregateFunction = getAggregateFunction;
87
- exports.processGroupBy = processGroupBy;
88
- //# sourceMappingURL=group-by.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"group-by.cjs","sources":["../../../src/query/group-by.ts"],"sourcesContent":["import { groupBy, groupByOperators } from \"@electric-sql/d2mini\"\nimport {\n evaluateOperandOnNamespacedRow,\n extractValueFromNamespacedRow,\n} from \"./extractors\"\nimport { isAggregateFunctionCall } from \"./utils\"\nimport type { ConditionOperand, FunctionCall, Query } from \"./schema\"\nimport type { NamespacedAndKeyedStream } from \"../types.js\"\n\nconst { sum, count, avg, min, max, median, mode } = groupByOperators\n\n/**\n * Process the groupBy clause in a D2QL query\n */\nexport function processGroupBy(\n pipeline: NamespacedAndKeyedStream,\n query: Query,\n mainTableAlias: string\n) {\n // Normalize groupBy to an array of column references\n const groupByColumns = Array.isArray(query.groupBy)\n ? query.groupBy\n : [query.groupBy]\n\n // Create a key extractor function for the groupBy operator\n const keyExtractor = ([_oldKey, namespacedRow]: [\n string,\n Record<string, unknown>,\n ]) => {\n const key: Record<string, unknown> = {}\n\n // Extract each groupBy column value\n for (const column of groupByColumns) {\n if (typeof column === `string` && (column as string).startsWith(`@`)) {\n const columnRef = (column as string).substring(1)\n const columnName = columnRef.includes(`.`)\n ? columnRef.split(`.`)[1]\n : columnRef\n\n key[columnName!] = extractValueFromNamespacedRow(\n namespacedRow,\n columnRef,\n mainTableAlias\n )\n }\n }\n\n return key\n }\n\n // Create aggregate functions for any aggregated columns in the SELECT clause\n const aggregates: Record<string, any> = {}\n\n if (!query.select) {\n throw new Error(`SELECT clause is required for GROUP BY`)\n }\n\n // Scan the SELECT clause for aggregate functions\n for (const item of query.select) {\n if (typeof item === `object`) {\n for (const [alias, expr] of Object.entries(item)) {\n if (typeof expr === `object` && isAggregateFunctionCall(expr)) {\n // Get the function name (the only key in the object)\n const functionName = Object.keys(expr)[0]\n // Get the column reference or expression to aggregate\n const columnRef = (expr as FunctionCall)[\n functionName as keyof FunctionCall\n ]\n\n // Add the aggregate function to our aggregates object\n aggregates[alias] = getAggregateFunction(\n functionName!,\n columnRef,\n mainTableAlias\n )\n }\n }\n }\n }\n\n // Apply the groupBy operator if we have any aggregates\n if (Object.keys(aggregates).length > 0) {\n pipeline = pipeline.pipe(groupBy(keyExtractor, aggregates))\n }\n\n return pipeline\n}\n\n/**\n * Helper function to get an aggregate function based on the function name\n */\nexport function getAggregateFunction(\n functionName: string,\n columnRef: string | ConditionOperand,\n mainTableAlias: string\n) {\n // Create a value extractor function for the column to aggregate\n const valueExtractor = ([_oldKey, namespacedRow]: [\n string,\n Record<string, unknown>,\n ]) => {\n let value: unknown\n if (typeof columnRef === `string` && columnRef.startsWith(`@`)) {\n value = extractValueFromNamespacedRow(\n namespacedRow,\n columnRef.substring(1),\n mainTableAlias\n )\n } else {\n value = evaluateOperandOnNamespacedRow(\n namespacedRow,\n columnRef as ConditionOperand,\n mainTableAlias\n )\n }\n // Ensure we return a number for aggregate functions\n return typeof value === `number` ? value : 0\n }\n\n // Return the appropriate aggregate function\n switch (functionName.toUpperCase()) {\n case `SUM`:\n return sum(valueExtractor)\n case `COUNT`:\n return count() // count() doesn't need a value extractor\n case `AVG`:\n return avg(valueExtractor)\n case `MIN`:\n return min(valueExtractor)\n case `MAX`:\n return max(valueExtractor)\n case `MEDIAN`:\n return median(valueExtractor)\n case `MODE`:\n return mode(valueExtractor)\n default:\n throw new Error(`Unsupported aggregate function: ${functionName}`)\n }\n}\n"],"names":["groupByOperators","extractValueFromNamespacedRow","isAggregateFunctionCall","groupBy","evaluateOperandOnNamespacedRow"],"mappings":";;;;;AASA,MAAM,EAAE,KAAK,OAAO,KAAK,KAAK,KAAK,QAAQ,SAASA,OAAA;AAKpC,SAAA,eACd,UACA,OACA,gBACA;AAEM,QAAA,iBAAiB,MAAM,QAAQ,MAAM,OAAO,IAC9C,MAAM,UACN,CAAC,MAAM,OAAO;AAGlB,QAAM,eAAe,CAAC,CAAC,SAAS,aAAa,MAGvC;AACJ,UAAM,MAA+B,CAAC;AAGtC,eAAW,UAAU,gBAAgB;AACnC,UAAI,OAAO,WAAW,YAAa,OAAkB,WAAW,GAAG,GAAG;AAC9D,cAAA,YAAa,OAAkB,UAAU,CAAC;AAC1C,cAAA,aAAa,UAAU,SAAS,GAAG,IACrC,UAAU,MAAM,GAAG,EAAE,CAAC,IACtB;AAEJ,YAAI,UAAW,IAAIC,WAAA;AAAA,UACjB;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MAAA;AAAA,IACF;AAGK,WAAA;AAAA,EACT;AAGA,QAAM,aAAkC,CAAC;AAErC,MAAA,CAAC,MAAM,QAAQ;AACX,UAAA,IAAI,MAAM,wCAAwC;A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C5B;AACE,YAAM,IAAI,MAAM,mCAAmC,YAAY,EAAE;AAAA,EAAA;AAEvE;;;"}
@@ -1,40 +0,0 @@
1
- import { ConditionOperand, Query } from './schema.cjs';
2
- import { NamespacedAndKeyedStream } from '../types.js';
3
- /**
4
- * Process the groupBy clause in a D2QL query
5
- */
6
- export declare function processGroupBy(pipeline: NamespacedAndKeyedStream, query: Query, mainTableAlias: string): NamespacedAndKeyedStream;
7
- /**
8
- * Helper function to get an aggregate function based on the function name
9
- */
10
- export declare function getAggregateFunction(functionName: string, columnRef: string | ConditionOperand, mainTableAlias: string): {
11
- preMap: (data: [string, Record<string, unknown>]) => number;
12
- reduce: (values: [number, number][]) => number;
13
- postMap?: ((result: number) => number) | undefined;
14
- } | {
15
- pipe: (stream: import('@electric-sql/d2mini').IStreamBuilder<[string, Record<string, unknown>]>) => import('@electric-sql/d2mini').IStreamBuilder<import('@electric-sql/d2mini').KeyValue<string, number>>;
16
- } | {
17
- preMap: (data: [string, Record<string, unknown>]) => {
18
- sum: number;
19
- count: number;
20
- };
21
- reduce: (values: [{
22
- sum: number;
23
- count: number;
24
- }, number][]) => {
25
- sum: number;
26
- count: number;
27
- };
28
- postMap?: ((result: {
29
- sum: number;
30
- count: number;
31
- }) => number) | undefined;
32
- } | {
33
- preMap: (data: [string, Record<string, unknown>]) => number[];
34
- reduce: (values: [number[], number][]) => number[];
35
- postMap?: ((result: number[]) => number) | undefined;
36
- } | {
37
- preMap: (data: [string, Record<string, unknown>]) => Map<number, number>;
38
- reduce: (values: [Map<number, number>, number][]) => Map<number, number>;
39
- postMap?: ((result: Map<number, number>) => number) | undefined;
40
- };
@@ -1,141 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const d2mini = require("@electric-sql/d2mini");
4
- const evaluators = require("./evaluators.cjs");
5
- const extractors = require("./extractors.cjs");
6
- function processJoinClause(pipeline, query, tables, mainTableAlias, allInputs) {
7
- if (!query.join) return pipeline;
8
- const input = allInputs[query.from];
9
- for (const joinClause of query.join) {
10
- const joinedTableAlias = joinClause.as || joinClause.from;
11
- const joinType = joinClause.type === `cross` ? `inner` : joinClause.type;
12
- const [mainKeyRef, , joinedKeyRefs] = joinClause.on;
13
- const mainPipeline = pipeline.pipe(
14
- d2mini.map(([currentKey, namespacedRow]) => {
15
- const mainRow = namespacedRow[mainTableAlias];
16
- const key = extractors.extractJoinKey(mainRow, mainKeyRef, mainTableAlias);
17
- return [key, [currentKey, namespacedRow]];
18
- })
19
- );
20
- let joinedTableInput;
21
- if (allInputs[joinClause.from]) {
22
- joinedTableInput = allInputs[joinClause.from];
23
- } else {
24
- joinedTableInput = input.graph.newInput();
25
- }
26
- tables[joinedTableAlias] = joinedTableInput;
27
- const joinedPipeline = joinedTableInput.pipe(
28
- d2mini.map(([currentKey, row]) => {
29
- const namespacedRow = { [joinedTableAlias]: row };
30
- const key = extractors.extractJoinKey(row, joinedKeyRefs, joinedTableAlias);
31
- return [key, [currentKey, namespacedRow]];
32
- })
33
- );
34
- switch (joinType) {
35
- case `inner`:
36
- pipeline = mainPipeline.pipe(
37
- d2mini.join(joinedPipeline, `inner`),
38
- d2mini.consolidate(),
39
- processJoinResults(mainTableAlias, joinedTableAlias, joinClause)
40
- );
41
- break;
42
- case `left`:
43
- pipeline = mainPipeline.pipe(
44
- d2mini.join(joinedPipeline, `left`),
45
- d2mini.consolidate(),
46
- processJoinResults(mainTableAlias, joinedTableAlias, joinClause)
47
- );
48
- break;
49
- case `right`:
50
- pipeline = mainPipeline.pipe(
51
- d2mini.join(joinedPipeline, `right`),
52
- d2mini.consolidate(),
53
- processJoinResults(mainTableAlias, joinedTableAlias, joinClause)
54
- );
55
- break;
56
- case `full`:
57
- pipeline = mainPipeline.pipe(
58
- d2mini.join(joinedPipeline, `full`),
59
- d2mini.consolidate(),
60
- processJoinResults(mainTableAlias, joinedTableAlias, joinClause)
61
- );
62
- break;
63
- default:
64
- pipeline = mainPipeline.pipe(
65
- d2mini.join(joinedPipeline, `inner`),
66
- d2mini.consolidate(),
67
- processJoinResults(mainTableAlias, joinedTableAlias, joinClause)
68
- );
69
- }
70
- }
71
- return pipeline;
72
- }
73
- function processJoinResults(mainTableAlias, joinedTableAlias, joinClause) {
74
- return function(pipeline) {
75
- return pipeline.pipe(
76
- // Process the join result and handle nulls in the same step
77
- d2mini.map((result) => {
78
- const [_key, [main, joined]] = result;
79
- const mainKey = main == null ? void 0 : main[0];
80
- const mainNamespacedRow = main == null ? void 0 : main[1];
81
- const joinedKey = joined == null ? void 0 : joined[0];
82
- const joinedNamespacedRow = joined == null ? void 0 : joined[1];
83
- if (joinClause.type === `inner` || joinClause.type === `cross`) {
84
- if (!mainNamespacedRow || !joinedNamespacedRow) {
85
- return void 0;
86
- }
87
- }
88
- if (joinClause.type === `left` && !mainNamespacedRow) {
89
- return void 0;
90
- }
91
- if (joinClause.type === `right` && !joinedNamespacedRow) {
92
- return void 0;
93
- }
94
- const mergedNamespacedRow = {};
95
- if (mainNamespacedRow) {
96
- Object.entries(mainNamespacedRow).forEach(
97
- ([tableAlias, tableData]) => {
98
- mergedNamespacedRow[tableAlias] = tableData;
99
- }
100
- );
101
- }
102
- if (joinedNamespacedRow) {
103
- Object.entries(joinedNamespacedRow).forEach(
104
- ([tableAlias, tableData]) => {
105
- mergedNamespacedRow[tableAlias] = tableData;
106
- }
107
- );
108
- } else if (joinClause.type === `left` || joinClause.type === `full`) ;
109
- if (!mainNamespacedRow && (joinClause.type === `right` || joinClause.type === `full`)) ;
110
- const newKey = `[${mainKey},${joinedKey}]`;
111
- return [newKey, mergedNamespacedRow];
112
- }),
113
- // Filter out undefined results
114
- d2mini.filter((value) => value !== void 0),
115
- // Process the ON condition
116
- d2mini.filter(([_key, namespacedRow]) => {
117
- if (!joinClause.on || joinClause.type === `cross`) {
118
- return true;
119
- }
120
- if (joinClause.type === `left` && namespacedRow[joinedTableAlias] === void 0) {
121
- return true;
122
- }
123
- if (joinClause.type === `right` && namespacedRow[mainTableAlias] === void 0) {
124
- return true;
125
- }
126
- if (joinClause.type === `full` && (namespacedRow[mainTableAlias] === void 0 || namespacedRow[joinedTableAlias] === void 0)) {
127
- return true;
128
- }
129
- return evaluators.evaluateConditionOnNamespacedRow(
130
- namespacedRow,
131
- joinClause.on,
132
- mainTableAlias,
133
- joinedTableAlias
134
- );
135
- })
136
- );
137
- };
138
- }
139
- exports.processJoinClause = processJoinClause;
140
- exports.processJoinResults = processJoinResults;
141
- //# sourceMappingURL=joins.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"joins.cjs","sources":["../../../src/query/joins.ts"],"sourcesContent":["import {\n consolidate,\n filter,\n join as joinOperator,\n map,\n} from \"@electric-sql/d2mini\"\nimport { evaluateConditionOnNamespacedRow } from \"./evaluators.js\"\nimport { extractJoinKey } from \"./extractors.js\"\nimport type { Query } from \"./index.js\"\nimport type { IStreamBuilder, JoinType } from \"@electric-sql/d2mini\"\nimport type {\n KeyedStream,\n NamespacedAndKeyedStream,\n NamespacedRow,\n} from \"../types.js\"\n\n/**\n * Creates a processing pipeline for join clauses\n */\nexport function processJoinClause(\n pipeline: NamespacedAndKeyedStream,\n query: Query,\n tables: Record<string, KeyedStream>,\n mainTableAlias: string,\n allInputs: Record<string, KeyedStream>\n) {\n if (!query.join) return pipeline\n const input = allInputs[query.from]\n\n for (const joinClause of query.join) {\n // Create a stream for the joined table\n const joinedTableAlias = joinClause.as || joinClause.from\n\n // Get the right join type for the operator\n const joinType: JoinType =\n joinClause.type === `cross` ? `inner` : joinClause.type\n\n // The `in` is formatted as ['@mainKeyRef', '=', '@joinedKeyRef']\n // Destructure the main key reference and the joined key references\n const [mainKeyRef, , joinedKeyRefs] = joinClause.on\n\n // We need to prepare the main pipeline and the joined pipeline\n // to have the correct key format for joining\n const mainPipeline = pipeline.pipe(\n map(([currentKey, namespacedRow]) => {\n // Extract the key from the ON condition left side for the main table\n const mainRow = namespacedRow[mainTableAlias]!\n\n // Extract the join key from the main row\n const key = extractJoinKey(mainRow, mainKeyRef, mainTableAlias)\n\n // Return [key, namespacedRow] as a KeyValue type\n return [key, [currentKey, namespacedRow]] as [\n unknown,\n [string, typeof namespacedRow],\n ]\n })\n )\n\n // Get the joined table input from the inputs map\n let joinedTableInput: KeyedStream\n\n if (allInputs[joinClause.from]) {\n // Use the provided input if available\n joinedTableInput = allInputs[joinClause.from]!\n } else {\n // Create a new input if not provided\n joinedTableInput =\n input!.graph.newInput<[string, Record<string, unknown>]>()\n }\n\n tables[joinedTableAlias] = joinedTableInput\n\n // Create a pipeline for the joined table\n const joinedPipeline = joinedTableInput.pipe(\n map(([currentKey, row]) => {\n // Wrap the row in an object with the table alias as the key\n const namespacedRow: NamespacedRow = { [joinedTableAlias]: row }\n\n // Extract the key from the ON condition right side for the joined table\n const key = extractJoinKey(row, joinedKeyRefs, joinedTableAlias)\n\n // Return [key, namespacedRow] as a KeyValue type\n return [key, [currentKey, namespacedRow]] as [\n string,\n [string, typeof namespacedRow],\n ]\n })\n )\n\n // Apply join with appropriate typings based on join type\n switch (joinType) {\n case `inner`:\n pipeline = mainPipeline.pipe(\n joinOperator(joinedPipeline, `inner`),\n consolidate(),\n processJoinResults(mainTableAlias, joinedTableAlias, joinClause)\n )\n break\n case `left`:\n pipeline = mainPipeline.pipe(\n joinOperator(joinedPipeline, `left`),\n consolidate(),\n processJoinResults(mainTableAlias, joinedTableAlias, joinClause)\n )\n break\n case `right`:\n pipeline = mainPipeline.pipe(\n joinOperator(joinedPipeline, `right`),\n consolidate(),\n processJoinResults(mainTableAlias, joinedTableAlias, joinClause)\n )\n break\n case `full`:\n pipeline = mainPipeline.pipe(\n joinOperator(joinedPipeline, `full`),\n consolidate(),\n processJoinResults(mainTableAlias, joinedTableAlias, joinClause)\n )\n break\n default:\n pipeline = mainPipeline.pipe(\n joinOperator(joinedPipeline, `inner`),\n consolidate(),\n processJoinResults(mainTableAlias, joinedTableAlias, joinClause)\n )\n }\n }\n return pipeline\n}\n\n/**\n * Creates a processing pipeline for join results\n */\nexport function processJoinResults(\n mainTableAlias: string,\n joinedTableAlias: string,\n joinClause: { on: any; type: string }\n) {\n return function (\n pipeline: IStreamBuilder<\n [\n key: string,\n [\n [string, NamespacedRow] | undefined,\n [string, NamespacedRow] | undefined,\n ],\n ]\n >\n ): NamespacedAndKeyedStream {\n return pipeline.pipe(\n // Process the join result and handle nulls in the same step\n map((result) => {\n const [_key, [main, joined]] = result\n const mainKey = main?.[0]\n const mainNamespacedRow = main?.[1]\n const joinedKey = joined?.[0]\n const joinedNamespacedRow = joined?.[1]\n\n // For inner joins, both sides should be non-null\n if (joinClause.type === `inner` || joinClause.type === `cross`) {\n if (!mainNamespacedRow || !joinedNamespacedRow) {\n return undefined // Will be filtered out\n }\n }\n\n // For left joins, the main row must be non-null\n if (joinClause.type === `left` && !mainNamespacedRow) {\n return undefined // Will be filtered out\n }\n\n // For right joins, the joined row must be non-null\n if (joinClause.type === `right` && !joinedNamespacedRow) {\n return undefined // Will be filtered out\n }\n\n // Merge the nested rows\n const mergedNamespacedRow: NamespacedRow = {}\n\n // Add main row data if it exists\n if (mainNamespacedRow) {\n Object.entries(mainNamespacedRow).forEach(\n ([tableAlias, tableData]) => {\n mergedNamespacedRow[tableAlias] = tableData\n }\n )\n }\n\n // If we have a joined row, add it to the merged result\n if (joinedNamespacedRow) {\n Object.entries(joinedNamespacedRow).forEach(\n ([tableAlias, tableData]) => {\n mergedNamespacedRow[tableAlias] = tableData\n }\n )\n } else if (joinClause.type === `left` || joinClause.type === `full`) {\n // For left or full joins, add the joined table with undefined data if missing\n // mergedNamespacedRow[joinedTableAlias] = undefined\n }\n\n // For right or full joins, add the main table with undefined data if missing\n if (\n !mainNamespacedRow &&\n (joinClause.type === `right` || joinClause.type === `full`)\n ) {\n // mergedNamespacedRow[mainTableAlias] = undefined\n }\n\n // New key\n const newKey = `[${mainKey},${joinedKey}]`\n\n return [newKey, mergedNamespacedRow] as [\n string,\n typeof mergedNamespacedRow,\n ]\n }),\n // Filter out undefined results\n filter((value) => value !== undefined),\n // Process the ON condition\n filter(([_key, namespacedRow]: [string, NamespacedRow]) => {\n // If there's no ON condition, or it's a cross join, always return true\n if (!joinClause.on || joinClause.type === `cross`) {\n return true\n }\n\n // For LEFT JOIN, if the right side is null, we should include the row\n if (\n joinClause.type === `left` &&\n namespacedRow[joinedTableAlias] === undefined\n ) {\n return true\n }\n\n // For RIGHT JOIN, if the left side is null, we should include the row\n if (\n joinClause.type === `right` &&\n namespacedRow[mainTableAlias] === undefined\n ) {\n return true\n }\n\n // For FULL JOIN, if either side is null, we should include the row\n if (\n joinClause.type === `full` &&\n (namespacedRow[mainTableAlias] === undefined ||\n namespacedRow[joinedTableAlias] === undefined)\n ) {\n return true\n }\n\n return evaluateConditionOnNamespacedRow(\n namespacedRow,\n joinClause.on,\n mainTableAlias,\n joinedTableAlias\n )\n })\n )\n }\n}\n"],"names":["map","extractJoinKey","joinOperator","consolidate","filter","evaluateConditionOnNamespacedRow"],"mappings":";;;;;AAmBO,SAAS,kBACd,UACA,OACA,QACA,gBACA,WACA;AACI,MAAA,CAAC,MAAM,KAAa,QAAA;AAClB,QAAA,QAAQ,UAAU,MAAM,IAAI;AAEvB,aAAA,cAAc,MAAM,MAAM;AAE7B,UAAA,mBAAmB,WAAW,MAAM,WAAW;AAGrD,UAAM,WACJ,WAAW,SAAS,UAAU,UAAU,WAAW;AAIrD,UAAM,CAAC,YAAA,EAAc,aAAa,IAAI,WAAW;AAIjD,UAAM,eAAe,SAAS;AAAA,MAC5BA,OAAAA,IAAI,CAAC,CAAC,YAAY,aAAa,MAAM;AAE7B,cAAA,UAAU,cAAc,cAAc;AAG5C,cAAM,MAAMC,WAAA,eAAe,SAAS,YAAY,cAAc;AAG9D,eAAO,CAAC,KAAK,CAAC,YAAY,aAAa,CAAC;AAAA,MAIzC,CAAA;AAAA,IACH;AAGI,QAAA;AAEA,QAAA,UAAU,WAAW,IAAI,GAAG;AAEX,yBAAA,UAAU,WAAW,IAAI;AAAA,IAAA,OAC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UACpB,cAAc,gBAAgB,MAAM,QACpC;AACO,iBAAA;AAAA,QAAA;AAIT,YACE,WAAW,SAAS,WACpB,cAAc,cAAc,MAAM,QAClC;AACO,iBAAA;AAAA,QAAA;AAKP,YAAA,WAAW,SAAS,WACnB,cAAc,cAAc,MAAM,UACjC,cAAc,gBAAgB,MAAM,SACtC;AACO,iBAAA;AAAA,QAAA;AAGF,eAAAC,WAAA;AAAA,UACL;AAAA,UACA,WAAW;AAAA,UACX;AAAA,UACA;AAAA,QACF;AAAA,MACD,CAAA;AAAA,IACH;AAAA,EACF;AACF;;;"}
@@ -1,14 +0,0 @@
1
- import { Query } from './index.js';
2
- import { IStreamBuilder } from '@electric-sql/d2mini';
3
- import { KeyedStream, NamespacedAndKeyedStream, NamespacedRow } from '../types.js';
4
- /**
5
- * Creates a processing pipeline for join clauses
6
- */
7
- export declare function processJoinClause(pipeline: NamespacedAndKeyedStream, query: Query, tables: Record<string, KeyedStream>, mainTableAlias: string, allInputs: Record<string, KeyedStream>): NamespacedAndKeyedStream;
8
- /**
9
- * Creates a processing pipeline for join results
10
- */
11
- export declare function processJoinResults(mainTableAlias: string, joinedTableAlias: string, joinClause: {
12
- on: any;
13
- type: string;
14
- }): (pipeline: IStreamBuilder<[key: string, [[string, NamespacedRow] | undefined, [string, NamespacedRow] | undefined]]>) => NamespacedAndKeyedStream;