@tanstack/db 0.0.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 +37 -0
- package/dist/cjs/SortedMap.cjs +140 -0
- package/dist/cjs/SortedMap.cjs.map +1 -0
- package/dist/cjs/SortedMap.d.cts +91 -0
- package/dist/cjs/collection.cjs +597 -0
- package/dist/cjs/collection.cjs.map +1 -0
- package/dist/cjs/collection.d.cts +176 -0
- package/dist/cjs/deferred.cjs +25 -0
- package/dist/cjs/deferred.cjs.map +1 -0
- package/dist/cjs/deferred.d.cts +20 -0
- package/dist/cjs/errors.cjs +10 -0
- package/dist/cjs/errors.cjs.map +1 -0
- package/dist/cjs/errors.d.cts +3 -0
- package/dist/cjs/index.cjs +33 -0
- package/dist/cjs/index.cjs.map +1 -0
- package/dist/cjs/index.d.cts +9 -0
- package/dist/cjs/proxy.cjs +654 -0
- package/dist/cjs/proxy.cjs.map +1 -0
- package/dist/cjs/proxy.d.cts +59 -0
- package/dist/cjs/query/compiled-query.cjs +162 -0
- package/dist/cjs/query/compiled-query.cjs.map +1 -0
- package/dist/cjs/query/compiled-query.d.cts +22 -0
- package/dist/cjs/query/evaluators.cjs +146 -0
- package/dist/cjs/query/evaluators.cjs.map +1 -0
- package/dist/cjs/query/evaluators.d.cts +9 -0
- package/dist/cjs/query/extractors.cjs +122 -0
- package/dist/cjs/query/extractors.cjs.map +1 -0
- package/dist/cjs/query/extractors.d.cts +22 -0
- package/dist/cjs/query/functions.cjs +152 -0
- package/dist/cjs/query/functions.cjs.map +1 -0
- package/dist/cjs/query/functions.d.cts +21 -0
- package/dist/cjs/query/group-by.cjs +91 -0
- package/dist/cjs/query/group-by.cjs.map +1 -0
- package/dist/cjs/query/group-by.d.cts +40 -0
- package/dist/cjs/query/index.d.cts +5 -0
- package/dist/cjs/query/joins.cjs +155 -0
- package/dist/cjs/query/joins.cjs.map +1 -0
- package/dist/cjs/query/joins.d.cts +14 -0
- package/dist/cjs/query/key-by.cjs +43 -0
- package/dist/cjs/query/key-by.cjs.map +1 -0
- package/dist/cjs/query/key-by.d.cts +3 -0
- package/dist/cjs/query/order-by.cjs +229 -0
- package/dist/cjs/query/order-by.cjs.map +1 -0
- package/dist/cjs/query/order-by.d.cts +3 -0
- package/dist/cjs/query/pipeline-compiler.cjs +94 -0
- package/dist/cjs/query/pipeline-compiler.cjs.map +1 -0
- package/dist/cjs/query/pipeline-compiler.d.cts +9 -0
- package/dist/cjs/query/query-builder.cjs +314 -0
- package/dist/cjs/query/query-builder.cjs.map +1 -0
- package/dist/cjs/query/query-builder.d.cts +219 -0
- package/dist/cjs/query/schema.d.cts +98 -0
- package/dist/cjs/query/select.cjs +107 -0
- package/dist/cjs/query/select.cjs.map +1 -0
- package/dist/cjs/query/select.d.cts +3 -0
- package/dist/cjs/query/types.d.cts +188 -0
- package/dist/cjs/query/utils.cjs +154 -0
- package/dist/cjs/query/utils.cjs.map +1 -0
- package/dist/cjs/query/utils.d.cts +37 -0
- package/dist/cjs/transactions.cjs +137 -0
- package/dist/cjs/transactions.cjs.map +1 -0
- package/dist/cjs/transactions.d.cts +27 -0
- package/dist/cjs/types.d.cts +94 -0
- package/dist/cjs/utils.cjs +17 -0
- package/dist/cjs/utils.cjs.map +1 -0
- package/dist/cjs/utils.d.cts +3 -0
- package/dist/esm/SortedMap.d.ts +91 -0
- package/dist/esm/SortedMap.js +140 -0
- package/dist/esm/SortedMap.js.map +1 -0
- package/dist/esm/collection.d.ts +176 -0
- package/dist/esm/collection.js +597 -0
- package/dist/esm/collection.js.map +1 -0
- package/dist/esm/deferred.d.ts +20 -0
- package/dist/esm/deferred.js +25 -0
- package/dist/esm/deferred.js.map +1 -0
- package/dist/esm/errors.d.ts +3 -0
- package/dist/esm/errors.js +10 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/index.d.ts +9 -0
- package/dist/esm/index.js +33 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/proxy.d.ts +59 -0
- package/dist/esm/proxy.js +654 -0
- package/dist/esm/proxy.js.map +1 -0
- package/dist/esm/query/compiled-query.d.ts +22 -0
- package/dist/esm/query/compiled-query.js +162 -0
- package/dist/esm/query/compiled-query.js.map +1 -0
- package/dist/esm/query/evaluators.d.ts +9 -0
- package/dist/esm/query/evaluators.js +146 -0
- package/dist/esm/query/evaluators.js.map +1 -0
- package/dist/esm/query/extractors.d.ts +22 -0
- package/dist/esm/query/extractors.js +122 -0
- package/dist/esm/query/extractors.js.map +1 -0
- package/dist/esm/query/functions.d.ts +21 -0
- package/dist/esm/query/functions.js +152 -0
- package/dist/esm/query/functions.js.map +1 -0
- package/dist/esm/query/group-by.d.ts +40 -0
- package/dist/esm/query/group-by.js +91 -0
- package/dist/esm/query/group-by.js.map +1 -0
- package/dist/esm/query/index.d.ts +5 -0
- package/dist/esm/query/joins.d.ts +14 -0
- package/dist/esm/query/joins.js +155 -0
- package/dist/esm/query/joins.js.map +1 -0
- package/dist/esm/query/key-by.d.ts +3 -0
- package/dist/esm/query/key-by.js +43 -0
- package/dist/esm/query/key-by.js.map +1 -0
- package/dist/esm/query/order-by.d.ts +3 -0
- package/dist/esm/query/order-by.js +229 -0
- package/dist/esm/query/order-by.js.map +1 -0
- package/dist/esm/query/pipeline-compiler.d.ts +9 -0
- package/dist/esm/query/pipeline-compiler.js +94 -0
- package/dist/esm/query/pipeline-compiler.js.map +1 -0
- package/dist/esm/query/query-builder.d.ts +219 -0
- package/dist/esm/query/query-builder.js +314 -0
- package/dist/esm/query/query-builder.js.map +1 -0
- package/dist/esm/query/schema.d.ts +98 -0
- package/dist/esm/query/select.d.ts +3 -0
- package/dist/esm/query/select.js +107 -0
- package/dist/esm/query/select.js.map +1 -0
- package/dist/esm/query/types.d.ts +188 -0
- package/dist/esm/query/utils.d.ts +37 -0
- package/dist/esm/query/utils.js +154 -0
- package/dist/esm/query/utils.js.map +1 -0
- package/dist/esm/transactions.d.ts +27 -0
- package/dist/esm/transactions.js +137 -0
- package/dist/esm/transactions.js.map +1 -0
- package/dist/esm/types.d.ts +94 -0
- package/dist/esm/utils.d.ts +3 -0
- package/dist/esm/utils.js +17 -0
- package/dist/esm/utils.js.map +1 -0
- package/package.json +57 -0
- package/src/SortedMap.ts +163 -0
- package/src/collection.ts +919 -0
- package/src/deferred.ts +47 -0
- package/src/errors.ts +6 -0
- package/src/index.ts +12 -0
- package/src/proxy.ts +1104 -0
- package/src/query/compiled-query.ts +193 -0
- package/src/query/evaluators.ts +222 -0
- package/src/query/extractors.ts +211 -0
- package/src/query/functions.ts +297 -0
- package/src/query/group-by.ts +137 -0
- package/src/query/index.ts +5 -0
- package/src/query/joins.ts +247 -0
- package/src/query/key-by.ts +61 -0
- package/src/query/order-by.ts +312 -0
- package/src/query/pipeline-compiler.ts +152 -0
- package/src/query/query-builder.ts +898 -0
- package/src/query/schema.ts +255 -0
- package/src/query/select.ts +173 -0
- package/src/query/types.ts +417 -0
- package/src/query/utils.ts +245 -0
- package/src/transactions.ts +198 -0
- package/src/types.ts +125 -0
- package/src/utils.ts +15 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extractors.js","sources":["../../../src/query/extractors.ts"],"sourcesContent":["import { evaluateFunction, isFunctionCall } from \"./functions.js\"\nimport type { AllowedFunctionName, ConditionOperand } from \"./schema.js\"\n\n/**\n * Extracts a value from a nested row structure\n * @param nestedRow The nested row structure\n * @param columnRef The column reference (may include table.column format)\n * @param mainTableAlias The main table alias to check first for columns without table reference\n * @param joinedTableAlias The joined table alias to check second for columns without table reference\n * @returns The extracted value or undefined if not found\n */\nexport function extractValueFromNestedRow(\n nestedRow: Record<string, unknown>,\n columnRef: string,\n mainTableAlias?: string,\n joinedTableAlias?: string\n): unknown {\n // Check if it's a table.column reference\n if (columnRef.includes(`.`)) {\n const [tableAlias, colName] = columnRef.split(`.`) as [string, string]\n\n // Get the table data\n const tableData = nestedRow[tableAlias] as\n | Record<string, unknown>\n | null\n | undefined\n\n if (!tableData) {\n return null\n }\n\n // Return the column value from that table\n const value = tableData[colName]\n return value\n } else {\n // If no table is specified, first try to find in the main table if provided\n if (mainTableAlias && nestedRow[mainTableAlias]) {\n const mainTableData = nestedRow[mainTableAlias] as Record<string, unknown>\n if (typeof mainTableData === `object` && columnRef in mainTableData) {\n return mainTableData[columnRef]\n }\n }\n\n // Then try the joined table if provided\n if (joinedTableAlias && nestedRow[joinedTableAlias]) {\n const joinedTableData = nestedRow[joinedTableAlias] as Record<\n string,\n unknown\n >\n if (typeof joinedTableData === `object` && columnRef in joinedTableData) {\n return joinedTableData[columnRef]\n }\n }\n\n // If not found in main or joined table, try to find the column in any table\n for (const [_tableAlias, tableData] of Object.entries(nestedRow)) {\n if (\n tableData &&\n typeof tableData === `object` &&\n columnRef in (tableData as Record<string, unknown>)\n ) {\n return (tableData as Record<string, unknown>)[columnRef]\n }\n }\n return undefined\n }\n}\n\n/**\n * Evaluates an operand against a nested row structure\n */\nexport function evaluateOperandOnNestedRow(\n nestedRow: Record<string, unknown>,\n operand: ConditionOperand,\n mainTableAlias?: string,\n joinedTableAlias?: string\n): unknown {\n // Handle column references\n if (typeof operand === `string` && operand.startsWith(`@`)) {\n const columnRef = operand.substring(1)\n return extractValueFromNestedRow(\n nestedRow,\n columnRef,\n mainTableAlias,\n joinedTableAlias\n )\n }\n\n // Handle explicit column references\n if (operand && typeof operand === `object` && `col` in operand) {\n const colRef = (operand as { col: unknown }).col\n\n if (typeof colRef === `string`) {\n // First try to extract from nested row structure\n const nestedValue = extractValueFromNestedRow(\n nestedRow,\n colRef,\n mainTableAlias,\n joinedTableAlias\n )\n\n // If not found in nested structure, check if it's a direct property of the row\n // This is important for HAVING clauses that reference aggregated values\n if (nestedValue === undefined && colRef in nestedRow) {\n return nestedRow[colRef]\n }\n\n return nestedValue\n }\n\n return undefined\n }\n\n // Handle function calls\n if (operand && typeof operand === `object` && isFunctionCall(operand)) {\n // Get the function name (the only key in the object)\n const functionName = Object.keys(operand)[0] as AllowedFunctionName\n // Get the arguments using type assertion with specific function name\n const args = (operand as any)[functionName]\n\n // If the arguments are a reference or another expression, evaluate them first\n const evaluatedArgs = Array.isArray(args)\n ? args.map((arg) =>\n evaluateOperandOnNestedRow(\n nestedRow,\n arg as ConditionOperand,\n mainTableAlias,\n joinedTableAlias\n )\n )\n : evaluateOperandOnNestedRow(\n nestedRow,\n args as ConditionOperand,\n mainTableAlias,\n joinedTableAlias\n )\n\n // Call the function with the evaluated arguments\n return evaluateFunction(\n functionName,\n evaluatedArgs as ConditionOperand | Array<ConditionOperand>\n )\n }\n\n // Handle explicit literals\n if (operand && typeof operand === `object` && `value` in operand) {\n return (operand as { value: unknown }).value\n }\n\n // Handle literal values\n return operand\n}\n\n/**\n * Extracts a join key value from a row based on the operand\n * @param row The data row (not nested)\n * @param operand The operand to extract the key from\n * @param defaultTableAlias The default table alias\n * @returns The extracted key value\n */\nexport function extractJoinKey<T extends Record<string, unknown>>(\n row: T,\n operand: ConditionOperand,\n defaultTableAlias?: string\n): unknown {\n let keyValue: unknown\n\n // Handle column references (e.g., \"@orders.id\" or \"@id\")\n if (typeof operand === `string` && operand.startsWith(`@`)) {\n const columnRef = operand.substring(1)\n\n // If it contains a dot, extract the table and column\n if (columnRef.includes(`.`)) {\n const [tableAlias, colName] = columnRef.split(`.`) as [string, string]\n // If this is referencing the current table, extract from row directly\n if (tableAlias === defaultTableAlias) {\n keyValue = row[colName]\n } else {\n // This might be a column from another table, return undefined\n keyValue = undefined\n }\n } else {\n // No table specified, look directly in the row\n keyValue = row[columnRef]\n }\n } else if (operand && typeof operand === `object` && `col` in operand) {\n // Handle explicit column references like { col: \"orders.id\" } or { col: \"id\" }\n const colRef = (operand as { col: unknown }).col\n\n if (typeof colRef === `string`) {\n if (colRef.includes(`.`)) {\n const [tableAlias, colName] = colRef.split(`.`) as [string, string]\n // If this is referencing the current table, extract from row directly\n if (tableAlias === defaultTableAlias) {\n keyValue = row[colName]\n } else {\n // This might be a column from another table, return undefined\n keyValue = undefined\n }\n } else {\n // No table specified, look directly in the row\n keyValue = row[colRef]\n }\n }\n } else {\n // Handle literals or other types\n keyValue = operand\n }\n\n return keyValue\n}\n"],"names":[],"mappings":";AAWO,SAAS,0BACd,WACA,WACA,gBACA,kBACS;AAEL,MAAA,UAAU,SAAS,GAAG,GAAG;AAC3B,UAAM,CAAC,YAAY,OAAO,IAAI,UAAU,MAAM,GAAG;AAG3C,UAAA,YAAY,UAAU,UAAU;AAKtC,QAAI,CAAC,WAAW;AACP,aAAA;AAAA,IAAA;AAIH,UAAA,QAAQ,UAAU,OAAO;AACxB,WAAA;AAAA,EAAA,OACF;AAED,QAAA,kBAAkB,UAAU,cAAc,GAAG;AACzC,YAAA,gBAAgB,UAAU,cAAc;AAC9C,UAAI,OAAO,kBAAkB,YAAY,aAAa,eAAe;AACnE,eAAO,cAAc,SAAS;AAAA,MAAA;AAAA,IAChC;AAIE,QAAA,oBAAoB,UAAU,gBAAgB,GAAG;AAC7C,YAAA,kBAAkB,UAAU,gBAAgB;AAIlD,UAAI,OAAO,oBAAoB,YAAY,aAAa,iBAAiB;AACvE,eAAO,gBAAgB,SAAS;AAAA,MAAA;AAAA,IAClC;AAIF,eAAW,CAAC,aAAa,SAAS,KAAK,OAAO,QAAQ,SAAS,GAAG;AAChE,UACE,aACA,OAAO,cAAc,YACrB,aAAc,WACd;AACA,eAAQ,UAAsC,SAAS;AAAA,MAAA;AAAA,IACzD;AAEK,WAAA;AAAA,EAAA;AAEX;AAKO,SAAS,2BACd,WACA,SACA,gBACA,kBACS;AAET,MAAI,OAAO,YAAY,YAAY,QAAQ,WAAW,GAAG,GAAG;AACpD,UAAA,YAAY,QAAQ,UAAU,CAAC;AAC9B,WAAA;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EAAA;AAIF,MAAI,WAAW,OAAO,YAAY,YAAY,SAAS,SAAS;AAC9D,UAAM,SAAU,QAA6B;AAEzC,QAAA,OAAO,WAAW,UAAU;AAE9B,YAAM,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,IAAI,OAAO,MAAM,GAAG;AAE9C,YAAI,eAAe,mBAAmB;AACpC,qBAAW,IAAI,OAAO;AAAA,QAAA,OACjB;AAEM,qBAAA;AAAA,QAAA;AAAA,MACb,OACK;AAEL,mBAAW,IAAI,MAAM;AAAA,MAAA;AAAA,IACvB;AAAA,EACF,OACK;AAEM,eAAA;AAAA,EAAA;AAGN,SAAA;AACT;"}
|
|
@@ -0,0 +1,21 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
function upperFunction(arg) {
|
|
2
|
+
if (typeof arg !== `string`) {
|
|
3
|
+
throw new Error(`UPPER function expects a string argument`);
|
|
4
|
+
}
|
|
5
|
+
return arg.toUpperCase();
|
|
6
|
+
}
|
|
7
|
+
function lowerFunction(arg) {
|
|
8
|
+
if (typeof arg !== `string`) {
|
|
9
|
+
throw new Error(`LOWER function expects a string argument`);
|
|
10
|
+
}
|
|
11
|
+
return arg.toLowerCase();
|
|
12
|
+
}
|
|
13
|
+
function lengthFunction(arg) {
|
|
14
|
+
if (typeof arg === `string` || Array.isArray(arg)) {
|
|
15
|
+
return arg.length;
|
|
16
|
+
}
|
|
17
|
+
throw new Error(`LENGTH function expects a string or array argument`);
|
|
18
|
+
}
|
|
19
|
+
function concatFunction(arg) {
|
|
20
|
+
if (!Array.isArray(arg)) {
|
|
21
|
+
throw new Error(`CONCAT function expects an array of string arguments`);
|
|
22
|
+
}
|
|
23
|
+
if (arg.length === 0) {
|
|
24
|
+
return ``;
|
|
25
|
+
}
|
|
26
|
+
for (let i = 0; i < arg.length; i++) {
|
|
27
|
+
if (arg[i] !== null && arg[i] !== void 0 && typeof arg[i] !== `string`) {
|
|
28
|
+
throw new Error(
|
|
29
|
+
`CONCAT function expects all arguments to be strings, but argument at position ${i} is ${typeof arg[i]}`
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return arg.map((str) => str === null || str === void 0 ? `` : str).join(``);
|
|
34
|
+
}
|
|
35
|
+
function coalesceFunction(arg) {
|
|
36
|
+
if (!Array.isArray(arg)) {
|
|
37
|
+
throw new Error(`COALESCE function expects an array of arguments`);
|
|
38
|
+
}
|
|
39
|
+
if (arg.length === 0) {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
for (const value of arg) {
|
|
43
|
+
if (value !== null && value !== void 0) {
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
function dateFunction(arg) {
|
|
50
|
+
if (arg instanceof Date) {
|
|
51
|
+
return arg;
|
|
52
|
+
}
|
|
53
|
+
if (arg === null || arg === void 0) {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
if (typeof arg === `string` || typeof arg === `number`) {
|
|
57
|
+
const date = new Date(arg);
|
|
58
|
+
if (isNaN(date.getTime())) {
|
|
59
|
+
throw new Error(`DATE function could not parse "${arg}" as a valid date`);
|
|
60
|
+
}
|
|
61
|
+
return date;
|
|
62
|
+
}
|
|
63
|
+
throw new Error(`DATE function expects a string, number, or Date argument`);
|
|
64
|
+
}
|
|
65
|
+
function jsonExtractFunction(arg) {
|
|
66
|
+
if (!Array.isArray(arg) || arg.length < 1) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
`JSON_EXTRACT function expects an array with at least one element [jsonInput, ...pathElements]`
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
const [jsonInput, ...pathElements] = arg;
|
|
72
|
+
if (jsonInput === null || jsonInput === void 0) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
let jsonData;
|
|
76
|
+
if (typeof jsonInput === `string`) {
|
|
77
|
+
try {
|
|
78
|
+
jsonData = JSON.parse(jsonInput);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
throw new Error(
|
|
81
|
+
`JSON_EXTRACT function could not parse JSON string: ${error instanceof Error ? error.message : String(error)}`
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
} else if (typeof jsonInput === `object`) {
|
|
85
|
+
jsonData = jsonInput;
|
|
86
|
+
} else {
|
|
87
|
+
throw new Error(
|
|
88
|
+
`JSON_EXTRACT function expects a JSON string or object as the first argument`
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
if (pathElements.length === 0) {
|
|
92
|
+
return jsonData;
|
|
93
|
+
}
|
|
94
|
+
let current = jsonData;
|
|
95
|
+
for (let i = 0; i < pathElements.length; i++) {
|
|
96
|
+
const pathElement = pathElements[i];
|
|
97
|
+
if (typeof pathElement !== `string`) {
|
|
98
|
+
throw new Error(
|
|
99
|
+
`JSON_EXTRACT function expects path elements to be strings, but element at position ${i + 1} is ${typeof pathElement}`
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
if (current === null || current === void 0 || typeof current !== `object`) {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
current = current[pathElement];
|
|
106
|
+
}
|
|
107
|
+
return current === void 0 ? null : current;
|
|
108
|
+
}
|
|
109
|
+
function orderIndexFunction(arg) {
|
|
110
|
+
if (arg !== `numeric` && arg !== `fractional` && arg !== true && arg !== `default`) {
|
|
111
|
+
throw new Error(
|
|
112
|
+
`ORDER_INDEX function expects "numeric", "fractional", "default", or true as argument`
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
const functionImplementations = {
|
|
118
|
+
// Map function names to their implementation functions
|
|
119
|
+
DATE: dateFunction,
|
|
120
|
+
JSON_EXTRACT: jsonExtractFunction,
|
|
121
|
+
JSON_EXTRACT_PATH: jsonExtractFunction,
|
|
122
|
+
// Alias for JSON_EXTRACT
|
|
123
|
+
UPPER: upperFunction,
|
|
124
|
+
LOWER: lowerFunction,
|
|
125
|
+
COALESCE: coalesceFunction,
|
|
126
|
+
CONCAT: concatFunction,
|
|
127
|
+
LENGTH: lengthFunction,
|
|
128
|
+
ORDER_INDEX: orderIndexFunction
|
|
129
|
+
};
|
|
130
|
+
function evaluateFunction(functionName, arg) {
|
|
131
|
+
const implementation = functionImplementations[functionName];
|
|
132
|
+
if (!implementation) {
|
|
133
|
+
throw new Error(`Unknown function: ${functionName}`);
|
|
134
|
+
}
|
|
135
|
+
return implementation(arg);
|
|
136
|
+
}
|
|
137
|
+
function isFunctionCall(obj) {
|
|
138
|
+
if (!obj || typeof obj !== `object`) {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
const keys = Object.keys(obj);
|
|
142
|
+
if (keys.length !== 1) {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
const functionName = keys[0];
|
|
146
|
+
return Object.keys(functionImplementations).includes(functionName);
|
|
147
|
+
}
|
|
148
|
+
export {
|
|
149
|
+
evaluateFunction,
|
|
150
|
+
isFunctionCall
|
|
151
|
+
};
|
|
152
|
+
//# sourceMappingURL=functions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"functions.js","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,KAAuB;AAC/C,MAAI,CAAC,MAAM,QAAQ,GAAG,GAAG;AACjB,UAAA,IAAI,MAAM,iDAAiD;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ilder } from '@electric-sql/d2ts';
|
|
3
|
+
/**
|
|
4
|
+
* Process the groupBy clause in a D2QL query
|
|
5
|
+
*/
|
|
6
|
+
export declare function processGroupBy(pipeline: IStreamBuilder<Record<string, unknown>>, query: Query, mainTableAlias: string): IStreamBuilder<Record<string, unknown>>;
|
|
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: Record<string, unknown>) => number;
|
|
12
|
+
reduce: (values: [number, number][]) => number;
|
|
13
|
+
postMap?: ((result: number) => number) | undefined;
|
|
14
|
+
} | {
|
|
15
|
+
pipe: (stream: IStreamBuilder<Record<string, unknown>>) => IStreamBuilder<import('@electric-sql/d2ts').KeyValue<string, number>>;
|
|
16
|
+
} | {
|
|
17
|
+
preMap: (data: 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: Record<string, unknown>) => number[];
|
|
34
|
+
reduce: (values: [number[], number][]) => number[];
|
|
35
|
+
postMap?: ((result: number[]) => number) | undefined;
|
|
36
|
+
} | {
|
|
37
|
+
preMap: (data: 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
|
+
};
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { groupBy, map, groupByOperators } from "@electric-sql/d2ts";
|
|
2
|
+
import { extractValueFromNestedRow, evaluateOperandOnNestedRow } from "./extractors.js";
|
|
3
|
+
import { isAggregateFunctionCall } from "./utils.js";
|
|
4
|
+
const { sum, count, avg, min, max, median, mode } = groupByOperators;
|
|
5
|
+
function processGroupBy(pipeline, query, mainTableAlias) {
|
|
6
|
+
const groupByColumns = Array.isArray(query.groupBy) ? query.groupBy : [query.groupBy];
|
|
7
|
+
const keyExtractor = (nestedRow) => {
|
|
8
|
+
const key = {};
|
|
9
|
+
for (const column of groupByColumns) {
|
|
10
|
+
if (typeof column === `string` && column.startsWith(`@`)) {
|
|
11
|
+
const columnRef = column.substring(1);
|
|
12
|
+
const columnName = columnRef.includes(`.`) ? columnRef.split(`.`)[1] : columnRef;
|
|
13
|
+
key[columnName] = extractValueFromNestedRow(
|
|
14
|
+
nestedRow,
|
|
15
|
+
columnRef,
|
|
16
|
+
mainTableAlias
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return key;
|
|
21
|
+
};
|
|
22
|
+
const aggregates = {};
|
|
23
|
+
for (const item of query.select) {
|
|
24
|
+
if (typeof item === `object`) {
|
|
25
|
+
for (const [alias, expr] of Object.entries(item)) {
|
|
26
|
+
if (typeof expr === `object` && isAggregateFunctionCall(expr)) {
|
|
27
|
+
const functionName = Object.keys(expr)[0];
|
|
28
|
+
const columnRef = expr[functionName];
|
|
29
|
+
aggregates[alias] = getAggregateFunction(
|
|
30
|
+
functionName,
|
|
31
|
+
columnRef,
|
|
32
|
+
mainTableAlias
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (Object.keys(aggregates).length > 0) {
|
|
39
|
+
pipeline = pipeline.pipe(
|
|
40
|
+
groupBy(keyExtractor, aggregates),
|
|
41
|
+
// Convert KeyValue<string, ResultType> to Record<string, unknown>
|
|
42
|
+
map(([_key, value]) => {
|
|
43
|
+
return value;
|
|
44
|
+
})
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
return pipeline;
|
|
48
|
+
}
|
|
49
|
+
function getAggregateFunction(functionName, columnRef, mainTableAlias) {
|
|
50
|
+
const valueExtractor = (nestedRow) => {
|
|
51
|
+
let value;
|
|
52
|
+
if (typeof columnRef === `string` && columnRef.startsWith(`@`)) {
|
|
53
|
+
value = extractValueFromNestedRow(
|
|
54
|
+
nestedRow,
|
|
55
|
+
columnRef.substring(1),
|
|
56
|
+
mainTableAlias
|
|
57
|
+
);
|
|
58
|
+
} else {
|
|
59
|
+
value = evaluateOperandOnNestedRow(
|
|
60
|
+
nestedRow,
|
|
61
|
+
columnRef,
|
|
62
|
+
mainTableAlias
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
return typeof value === `number` ? value : 0;
|
|
66
|
+
};
|
|
67
|
+
switch (functionName.toUpperCase()) {
|
|
68
|
+
case `SUM`:
|
|
69
|
+
return sum(valueExtractor);
|
|
70
|
+
case `COUNT`:
|
|
71
|
+
return count();
|
|
72
|
+
// count() doesn't need a value extractor
|
|
73
|
+
case `AVG`:
|
|
74
|
+
return avg(valueExtractor);
|
|
75
|
+
case `MIN`:
|
|
76
|
+
return min(valueExtractor);
|
|
77
|
+
case `MAX`:
|
|
78
|
+
return max(valueExtractor);
|
|
79
|
+
case `MEDIAN`:
|
|
80
|
+
return median(valueExtractor);
|
|
81
|
+
case `MODE`:
|
|
82
|
+
return mode(valueExtractor);
|
|
83
|
+
default:
|
|
84
|
+
throw new Error(`Unsupported aggregate function: ${functionName}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
export {
|
|
88
|
+
getAggregateFunction,
|
|
89
|
+
processGroupBy
|
|
90
|
+
};
|
|
91
|
+
//# sourceMappingURL=group-by.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"group-by.js","sources":["../../../src/query/group-by.ts"],"sourcesContent":["import { groupBy, groupByOperators, map } from \"@electric-sql/d2ts\"\nimport {\n evaluateOperandOnNestedRow,\n extractValueFromNestedRow,\n} from \"./extractors\"\nimport { isAggregateFunctionCall } from \"./utils\"\nimport type { ConditionOperand, FunctionCall, Query } from \"./schema\"\nimport type { IStreamBuilder } from \"@electric-sql/d2ts\"\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: IStreamBuilder<Record<string, unknown>>,\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 = (nestedRow: Record<string, unknown>) => {\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!] = extractValueFromNestedRow(\n nestedRow,\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 // 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(\n groupBy(keyExtractor, aggregates),\n // Convert KeyValue<string, ResultType> to Record<string, unknown>\n map(([_key, value]) => {\n // After groupBy, the value already contains both the key fields and aggregate results\n // We need to return it as is, not wrapped in a nested structure\n return value as Record<string, unknown>\n })\n )\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 = (nestedRow: Record<string, unknown>) => {\n let value: unknown\n if (typeof columnRef === `string` && columnRef.startsWith(`@`)) {\n value = extractValueFromNestedRow(\n nestedRow,\n columnRef.substring(1),\n mainTableAlias\n )\n } else {\n value = evaluateOperandOnNestedRow(\n nestedRow,\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":[],"mappings":";;;AASA,MAAM,EAAE,KAAK,OAAO,KAAK,KAAK,KAAK,QAAQ,SAAS;AAKpC,SAAA,eACd,UACA,OACA,gBACA;AAEM,QAAA,iBAAiB,MAAM,QAAQ,MAAM,OAAO,IAC9C,MAAM,UACN,CAAC,MAAM,OAAO;AAGZ,QAAA,eAAe,CAAC,cAAuC;AAC3D,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,IAAI;AAAA,UACjB;A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AAc;AAAA,IAC3B,KAAK;AACH,aAAO,IAAI,cAAc;AAAA,IAC3B,KAAK;AACH,aAAO,OAAO,cAAc;AAAA,IAC9B,KAAK;AACH,aAAO,KAAK,cAAc;AAAA,IAC5B;AACE,YAAM,IAAI,MAAM,mCAAmC,YAAY,EAAE;AAAA,EAAA;AAEvE;"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Query } from './index.js';
|
|
2
|
+
import { IStreamBuilder } from '@electric-sql/d2ts';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a processing pipeline for join clauses
|
|
5
|
+
*/
|
|
6
|
+
export declare function processJoinClause(pipeline: IStreamBuilder<Record<string, unknown>>, query: Query, tables: Record<string, IStreamBuilder<Record<string, unknown>>>, mainTableAlias: string, allInputs: Record<string, IStreamBuilder<Record<string, unknown>>>): IStreamBuilder<Record<string, unknown>>;
|
|
7
|
+
/**
|
|
8
|
+
* Creates a processing pipeline for join results
|
|
9
|
+
*/
|
|
10
|
+
export declare function processJoinResults(mainTableAlias: string, joinedTableAlias: string, joinClause: {
|
|
11
|
+
on: any;
|
|
12
|
+
where?: any;
|
|
13
|
+
type: string;
|
|
14
|
+
}): (pipeline: IStreamBuilder<unknown>) => IStreamBuilder<Record<string, unknown>>;
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { map, join, consolidate, filter } from "@electric-sql/d2ts";
|
|
2
|
+
import { evaluateConditionOnNestedRow } from "./evaluators.js";
|
|
3
|
+
import { extractJoinKey } from "./extractors.js";
|
|
4
|
+
function processJoinClause(pipeline, query, tables, mainTableAlias, allInputs) {
|
|
5
|
+
if (!query.join) return pipeline;
|
|
6
|
+
const input = allInputs[query.from];
|
|
7
|
+
for (const joinClause of query.join) {
|
|
8
|
+
const joinedTableAlias = joinClause.as || joinClause.from;
|
|
9
|
+
const joinType = joinClause.type === `cross` ? `inner` : joinClause.type;
|
|
10
|
+
const mainPipeline = pipeline.pipe(
|
|
11
|
+
map((nestedRow) => {
|
|
12
|
+
const mainRow = nestedRow[mainTableAlias];
|
|
13
|
+
const keyValue = extractJoinKey(
|
|
14
|
+
mainRow,
|
|
15
|
+
joinClause.on[0],
|
|
16
|
+
mainTableAlias
|
|
17
|
+
);
|
|
18
|
+
return [keyValue, nestedRow];
|
|
19
|
+
})
|
|
20
|
+
);
|
|
21
|
+
let joinedTableInput;
|
|
22
|
+
if (allInputs[joinClause.from]) {
|
|
23
|
+
joinedTableInput = allInputs[joinClause.from];
|
|
24
|
+
} else {
|
|
25
|
+
joinedTableInput = input.graph.newInput();
|
|
26
|
+
}
|
|
27
|
+
tables[joinedTableAlias] = joinedTableInput;
|
|
28
|
+
const joinedPipeline = joinedTableInput.pipe(
|
|
29
|
+
map((row) => {
|
|
30
|
+
const nestedRow = { [joinedTableAlias]: row };
|
|
31
|
+
const keyValue = extractJoinKey(row, joinClause.on[2], joinedTableAlias);
|
|
32
|
+
return [keyValue, nestedRow];
|
|
33
|
+
})
|
|
34
|
+
);
|
|
35
|
+
switch (joinType) {
|
|
36
|
+
case `inner`:
|
|
37
|
+
pipeline = mainPipeline.pipe(
|
|
38
|
+
join(joinedPipeline, `inner`),
|
|
39
|
+
consolidate(),
|
|
40
|
+
processJoinResults(mainTableAlias, joinedTableAlias, joinClause)
|
|
41
|
+
);
|
|
42
|
+
break;
|
|
43
|
+
case `left`:
|
|
44
|
+
pipeline = mainPipeline.pipe(
|
|
45
|
+
join(joinedPipeline, `left`),
|
|
46
|
+
consolidate(),
|
|
47
|
+
processJoinResults(mainTableAlias, joinedTableAlias, joinClause)
|
|
48
|
+
);
|
|
49
|
+
break;
|
|
50
|
+
case `right`:
|
|
51
|
+
pipeline = mainPipeline.pipe(
|
|
52
|
+
join(joinedPipeline, `right`),
|
|
53
|
+
consolidate(),
|
|
54
|
+
processJoinResults(mainTableAlias, joinedTableAlias, joinClause)
|
|
55
|
+
);
|
|
56
|
+
break;
|
|
57
|
+
case `full`:
|
|
58
|
+
pipeline = mainPipeline.pipe(
|
|
59
|
+
join(joinedPipeline, `full`),
|
|
60
|
+
consolidate(),
|
|
61
|
+
processJoinResults(mainTableAlias, joinedTableAlias, joinClause)
|
|
62
|
+
);
|
|
63
|
+
break;
|
|
64
|
+
default:
|
|
65
|
+
pipeline = mainPipeline.pipe(
|
|
66
|
+
join(joinedPipeline, `inner`),
|
|
67
|
+
consolidate(),
|
|
68
|
+
processJoinResults(mainTableAlias, joinedTableAlias, joinClause)
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return pipeline;
|
|
73
|
+
}
|
|
74
|
+
function processJoinResults(mainTableAlias, joinedTableAlias, joinClause) {
|
|
75
|
+
return function(pipeline) {
|
|
76
|
+
return pipeline.pipe(
|
|
77
|
+
// Process the join result and handle nulls in the same step
|
|
78
|
+
map((result) => {
|
|
79
|
+
const [_key, [mainNestedRow, joinedNestedRow]] = result;
|
|
80
|
+
if (joinClause.type === `inner` || joinClause.type === `cross`) {
|
|
81
|
+
if (!mainNestedRow || !joinedNestedRow) {
|
|
82
|
+
return void 0;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (joinClause.type === `left` && !mainNestedRow) {
|
|
86
|
+
return void 0;
|
|
87
|
+
}
|
|
88
|
+
if (joinClause.type === `right` && !joinedNestedRow) {
|
|
89
|
+
return void 0;
|
|
90
|
+
}
|
|
91
|
+
const mergedNestedRow = {};
|
|
92
|
+
if (mainNestedRow) {
|
|
93
|
+
Object.entries(mainNestedRow).forEach(([tableAlias, tableData]) => {
|
|
94
|
+
mergedNestedRow[tableAlias] = tableData;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
if (joinedNestedRow) {
|
|
98
|
+
Object.entries(joinedNestedRow).forEach(([tableAlias, tableData]) => {
|
|
99
|
+
mergedNestedRow[tableAlias] = tableData;
|
|
100
|
+
});
|
|
101
|
+
} else if (joinClause.type === `left` || joinClause.type === `full`) {
|
|
102
|
+
mergedNestedRow[joinedTableAlias] = null;
|
|
103
|
+
}
|
|
104
|
+
if (!mainNestedRow && (joinClause.type === `right` || joinClause.type === `full`)) {
|
|
105
|
+
mergedNestedRow[mainTableAlias] = null;
|
|
106
|
+
}
|
|
107
|
+
return mergedNestedRow;
|
|
108
|
+
}),
|
|
109
|
+
// Filter out undefined results
|
|
110
|
+
filter(
|
|
111
|
+
(value) => value !== void 0
|
|
112
|
+
),
|
|
113
|
+
// Process the ON condition
|
|
114
|
+
filter((nestedRow) => {
|
|
115
|
+
if (!joinClause.on || joinClause.type === `cross`) {
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
if (joinClause.type === `left` && nestedRow[joinedTableAlias] === null) {
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
if (joinClause.type === `right` && nestedRow[mainTableAlias] === null) {
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
if (joinClause.type === `full` && (nestedRow[mainTableAlias] === null || nestedRow[joinedTableAlias] === null)) {
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
const result = evaluateConditionOnNestedRow(
|
|
128
|
+
nestedRow,
|
|
129
|
+
joinClause.on,
|
|
130
|
+
mainTableAlias,
|
|
131
|
+
joinedTableAlias
|
|
132
|
+
);
|
|
133
|
+
return result;
|
|
134
|
+
}),
|
|
135
|
+
// Process the WHERE clause for the join if it exists
|
|
136
|
+
filter((nestedRow) => {
|
|
137
|
+
if (!joinClause.where) {
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
const result = evaluateConditionOnNestedRow(
|
|
141
|
+
nestedRow,
|
|
142
|
+
joinClause.where,
|
|
143
|
+
mainTableAlias,
|
|
144
|
+
joinedTableAlias
|
|
145
|
+
);
|
|
146
|
+
return result;
|
|
147
|
+
})
|
|
148
|
+
);
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
export {
|
|
152
|
+
processJoinClause,
|
|
153
|
+
processJoinResults
|
|
154
|
+
};
|
|
155
|
+
//# sourceMappingURL=joins.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"joins.js","sources":["../../../src/query/joins.ts"],"sourcesContent":["import {\n consolidate,\n filter,\n join as joinOperator,\n map,\n} from \"@electric-sql/d2ts\"\nimport { evaluateConditionOnNestedRow } from \"./evaluators.js\"\nimport { extractJoinKey } from \"./extractors.js\"\nimport type { Query } from \"./index.js\"\nimport type { IStreamBuilder, JoinType } from \"@electric-sql/d2ts\"\n\n/**\n * Creates a processing pipeline for join clauses\n */\nexport function processJoinClause(\n pipeline: IStreamBuilder<Record<string, unknown>>,\n query: Query,\n tables: Record<string, IStreamBuilder<Record<string, unknown>>>,\n mainTableAlias: string,\n allInputs: Record<string, IStreamBuilder<Record<string, unknown>>>\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 // 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((nestedRow: Record<string, unknown>) => {\n // Extract the key from the ON condition left side for the main table\n const mainRow = nestedRow[mainTableAlias] as Record<string, unknown>\n\n // Extract the join key from the main row\n const keyValue = extractJoinKey(\n mainRow,\n joinClause.on[0],\n mainTableAlias\n )\n\n // Return [key, nestedRow] as a KeyValue type\n return [keyValue, nestedRow] as [unknown, Record<string, unknown>]\n })\n )\n\n // Get the joined table input from the inputs map\n let joinedTableInput: IStreamBuilder<Record<string, unknown>>\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 = input!.graph.newInput<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((row: Record<string, unknown>) => {\n // Wrap the row in an object with the table alias as the key\n const nestedRow = { [joinedTableAlias]: row }\n\n // Extract the key from the ON condition right side for the joined table\n const keyValue = extractJoinKey(row, joinClause.on[2], joinedTableAlias)\n\n // Return [key, nestedRow] as a KeyValue type\n return [keyValue, nestedRow] as [unknown, Record<string, unknown>]\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; where?: any; type: string }\n) {\n return function (\n pipeline: IStreamBuilder<unknown>\n ): IStreamBuilder<Record<string, unknown>> {\n return pipeline.pipe(\n // Process the join result and handle nulls in the same step\n map((result: unknown) => {\n const [_key, [mainNestedRow, joinedNestedRow]] = result as [\n unknown,\n [\n Record<string, unknown> | undefined,\n Record<string, unknown> | undefined,\n ],\n ]\n\n // For inner joins, both sides should be non-null\n if (joinClause.type === `inner` || joinClause.type === `cross`) {\n if (!mainNestedRow || !joinedNestedRow) {\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` && !mainNestedRow) {\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` && !joinedNestedRow) {\n return undefined // Will be filtered out\n }\n\n // Merge the nested rows\n const mergedNestedRow: Record<string, unknown> = {}\n\n // Add main row data if it exists\n if (mainNestedRow) {\n Object.entries(mainNestedRow).forEach(([tableAlias, tableData]) => {\n mergedNestedRow[tableAlias] = tableData\n })\n }\n\n // If we have a joined row, add it to the merged result\n if (joinedNestedRow) {\n Object.entries(joinedNestedRow).forEach(([tableAlias, tableData]) => {\n mergedNestedRow[tableAlias] = tableData\n })\n } else if (joinClause.type === `left` || joinClause.type === `full`) {\n // For left or full joins, add the joined table with null data if missing\n mergedNestedRow[joinedTableAlias] = null\n }\n\n // For right or full joins, add the main table with null data if missing\n if (\n !mainNestedRow &&\n (joinClause.type === `right` || joinClause.type === `full`)\n ) {\n mergedNestedRow[mainTableAlias] = null\n }\n\n return mergedNestedRow\n }),\n // Filter out undefined results\n filter(\n (value: unknown): value is Record<string, unknown> =>\n value !== undefined\n ),\n // Process the ON condition\n filter((nestedRow: Record<string, unknown>) => {\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 nestedRow[joinedTableAlias] === null\n ) {\n return true\n }\n\n // For RIGHT JOIN, if the left side is null, we should include the row\n if (joinClause.type === `right` && nestedRow[mainTableAlias] === null) {\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 (nestedRow[mainTableAlias] === null ||\n nestedRow[joinedTableAlias] === null)\n ) {\n return true\n }\n\n const result = evaluateConditionOnNestedRow(\n nestedRow,\n joinClause.on,\n mainTableAlias,\n joinedTableAlias\n )\n return result\n }),\n // Process the WHERE clause for the join if it exists\n filter((nestedRow: Record<string, unknown>) => {\n if (!joinClause.where) {\n return true\n }\n\n const result = evaluateConditionOnNestedRow(\n nestedRow,\n jo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AA,UAAA,CAC/B;AAAA,QAAA,WACQ,WAAW,SAAS,UAAU,WAAW,SAAS,QAAQ;AAEnE,0BAAgB,gBAAgB,IAAI;AAAA,QAAA;AAItC,YACE,CAAC,kBACA,WAAW,SAAS,WAAW,WAAW,SAAS,SACpD;AACA,0BAAgB,cAAc,IAAI;AAAA,QAAA;AAG7B,eAAA;AAAA,MAAA,CACR;AAAA;AAAA,MAED;AAAA,QACE,CAAC,UACC,UAAU;AAAA,MACd;AAAA;AAAA,MAEA,OAAO,CAAC,cAAuC;AAE7C,YAAI,CAAC,WAAW,MAAM,WAAW,SAAS,SAAS;AAC1C,iBAAA;AAAA,QAAA;AAIT,YACE,WAAW,SAAS,UACpB,UAAU,gBAAgB,MAAM,MAChC;AACO,iBAAA;AAAA,QAAA;AAIT,YAAI,WAAW,SAAS,WAAW,UAAU,cAAc,MAAM,MAAM;AAC9D,iBAAA;AAAA,QAAA;AAKP,YAAA,WAAW,SAAS,WACnB,UAAU,cAAc,MAAM,QAC7B,UAAU,gBAAgB,MAAM,OAClC;AACO,iBAAA;AAAA,QAAA;AAGT,cAAM,SAAS;AAAA,UACb;AAAA,UACA,WAAW;AAAA,UACX;AAAA,UACA;AAAA,QACF;AACO,eAAA;AAAA,MAAA,CACR;AAAA;AAAA,MAED,OAAO,CAAC,cAAuC;AACzC,YAAA,CAAC,WAAW,OAAO;AACd,iBAAA;AAAA,QAAA;AAGT,cAAM,SAAS;AAAA,UACb;AAAA,UACA,WAAW;AAAA,UACX;AAAA,UACA;AAAA,QACF;AACO,eAAA;AAAA,MACR,CAAA;AAAA,IACH;AAAA,EACF;AACF;"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { IStreamBuilder } from '@electric-sql/d2ts';
|
|
2
|
+
import { Query } from './schema.js';
|
|
3
|
+
export declare function processKeyBy(resultPipeline: IStreamBuilder<Record<string, unknown> | [string | number, Record<string, unknown>]>, query: Query): IStreamBuilder<Record<string, unknown> | [string | number, Record<string, unknown>]>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { keyBy } from "@electric-sql/d2ts";
|
|
2
|
+
function processKeyBy(resultPipeline, query) {
|
|
3
|
+
if (!query.keyBy) {
|
|
4
|
+
return resultPipeline;
|
|
5
|
+
}
|
|
6
|
+
const keyByParam = query.keyBy;
|
|
7
|
+
resultPipeline = resultPipeline.pipe(
|
|
8
|
+
keyBy((row) => {
|
|
9
|
+
if (Array.isArray(keyByParam)) {
|
|
10
|
+
const keyValues = {};
|
|
11
|
+
for (const keyColumn of keyByParam) {
|
|
12
|
+
const columnName = keyColumn.startsWith(`@`) ? keyColumn.substring(1) : keyColumn;
|
|
13
|
+
if (columnName in row) {
|
|
14
|
+
keyValues[columnName] = row[columnName];
|
|
15
|
+
} else {
|
|
16
|
+
throw new Error(
|
|
17
|
+
`Key column "${columnName}" not found in result set. Make sure it's included in the select clause.`
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return JSON.stringify(keyValues);
|
|
22
|
+
} else {
|
|
23
|
+
const columnName = keyByParam.startsWith(`@`) ? keyByParam.substring(1) : keyByParam;
|
|
24
|
+
if (!(columnName in row)) {
|
|
25
|
+
throw new Error(
|
|
26
|
+
`Key column "${columnName}" not found in result set. Make sure it's included in the select clause.`
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
const keyValue = row[columnName];
|
|
30
|
+
if (typeof keyValue === `string` || typeof keyValue === `number`) {
|
|
31
|
+
return keyValue;
|
|
32
|
+
} else {
|
|
33
|
+
return JSON.stringify(keyValue);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
})
|
|
37
|
+
);
|
|
38
|
+
return resultPipeline;
|
|
39
|
+
}
|
|
40
|
+
export {
|
|
41
|
+
processKeyBy
|
|
42
|
+
};
|
|
43
|
+
//# sourceMappingURL=key-by.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"key-by.js","sources":["../../../src/query/key-by.ts"],"sourcesContent":["import { keyBy } from \"@electric-sql/d2ts\"\nimport type { IStreamBuilder } from \"@electric-sql/d2ts\"\nimport type { Query } from \"./schema\"\n\nexport function processKeyBy(\n resultPipeline: IStreamBuilder<\n Record<string, unknown> | [string | number, Record<string, unknown>]\n >,\n query: Query\n) {\n if (!query.keyBy) {\n return resultPipeline\n }\n const keyByParam = query.keyBy\n\n resultPipeline = resultPipeline.pipe(\n keyBy((row: Record<string, unknown>) => {\n if (Array.isArray(keyByParam)) {\n // Multiple columns - extract values and JSON stringify\n const keyValues: Record<string, unknown> = {}\n for (const keyColumn of keyByParam) {\n // Remove @ prefix if present\n const columnName = (keyColumn as string).startsWith(`@`)\n ? (keyColumn as string).substring(1)\n : (keyColumn as string)\n\n if (columnName in row) {\n keyValues[columnName] = row[columnName]\n } else {\n throw new Error(\n `Key column \"${columnName}\" not found in result set. Make sure it's included in the select clause.`\n )\n }\n }\n return JSON.stringify(keyValues)\n } else {\n // Single column\n // Remove @ prefix if present\n const columnName = (keyByParam as string).startsWith(`@`)\n ? (keyByParam as string).substring(1)\n : (keyByParam as string)\n\n if (!(columnName in row)) {\n throw new Error(\n `Key column \"${columnName}\" not found in result set. Make sure it's included in the select clause.`\n )\n }\n\n const keyValue = row[columnName]\n // Use the value directly if it's a string or number, otherwise JSON stringify\n if (typeof keyValue === `string` || typeof keyValue === `number`) {\n return keyValue\n } else {\n return JSON.stringify(keyValue)\n }\n }\n })\n )\n\n return resultPipeline\n}\n"],"names":[],"mappings":";AAIgB,SAAA,aACd,gBAGA,OACA;AACI,MAAA,CAAC,MAAM,OAAO;AACT,WAAA;AAAA,EAAA;AAET,QAAM,aAAa,MAAM;AAEzB,mBAAiB,eAAe;AAAA,IAC9B,MAAM,CAAC,QAAiC;AAClC,UAAA,MAAM,QAAQ,UAAU,GAAG;AAE7B,cAAM,YAAqC,CAAC;AAC5C,mBAAW,aAAa,YAAY;AAE5B,gBAAA,aAAc,UAAqB,WAAW,GAAG,IAClD,UAAqB,UAAU,CAAC,IAChC;AAEL,cAAI,cAAc,KAAK;AACX,sBAAA,UAAU,IAAI,IAAI,UAAU;AAAA,UAAA,OACjC;AACL,kBAAM,IAAI;AAAA,cACR,eAAe,UAAU;AAAA,YAC3B;AAAA,UAAA;AAAA,QACF;AAEK,eAAA,KAAK,UAAU,SAAS;AAAA,MAAA,OAC1B;AAGC,cAAA,aAAc,WAAsB,WAAW,GAAG,IACnD,WAAsB,UAAU,CAAC,IACjC;AAED,YAAA,EAAE,cAAc,MAAM;AACxB,gBAAM,IAAI;AAAA,YACR,eAAe,UAAU;AAAA,UAC3B;AAAA,QAAA;AAGI,cAAA,WAAW,IAAI,UAAU;AAE/B,YAAI,OAAO,aAAa,YAAY,OAAO,aAAa,UAAU;AACzD,iBAAA;AAAA,QAAA,OACF;AACE,iBAAA,KAAK,UAAU,QAAQ;AAAA,QAAA;AAAA,MAChC;AAAA,IAEH,CAAA;AAAA,EACH;AAEO,SAAA;AACT;"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { Query } from './schema.js';
|
|
2
|
+
import { IStreamBuilder } from '@electric-sql/d2ts';
|
|
3
|
+
export declare function processOrderBy(resultPipeline: IStreamBuilder<Record<string, unknown> | [string | number, Record<string, unknown>]>, query: Query, mainTableAlias: string): IStreamBuilder<Record<string, unknown> | [string | number, Record<string, unknown>]>;
|