forked from GoogleCloudPlatform/bigquery-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject_agg.sqlx
More file actions
61 lines (57 loc) · 2.04 KB
/
Copy pathobject_agg.sqlx
File metadata and controls
61 lines (57 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
config { hasOutput: true }
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
CREATE OR REPLACE AGGREGATE FUNCTION ${self()}(
key STRING,
value JSON,
allow_duplicate_pairs BOOL NOT AGGREGATE)
RETURNS JSON
LANGUAGE js
OPTIONS (
description = "Emulation of Snowflake's OBJECT_AGG function."
) AS r"""
export function initialState() {
return {obj: {}, allow_duplicate_pairs: false};
}
export function aggregate(state, key, value, allow_duplicate_pairs) {
state.allow_duplicate_pairs = allow_duplicate_pairs;
if (key === null || value === null) {
return;
}
if (Object.hasOwn(state.obj, key) && (!allow_duplicate_pairs || state.obj[key] !== value)) {
throw new Error("Duplicate field key '" + key + "'");
}
state.obj[key] = value;
}
export function merge(state, partialState) {
const stateKeys = Object.keys(state.obj);
const partialStateKeys = Object.keys(partialState.obj);
const [smallerKeys, largerObj, smallerObj] = stateKeys.length < partialStateKeys.length
? [stateKeys, partialState.obj, state.obj]
: [partialStateKeys, state.obj, partialState.obj];
for (let i = 0; i < smallerKeys.length; i++) {
const key = smallerKeys[i];
if (Object.hasOwn(largerObj, key) &&
(!state.allow_duplicate_pairs || largerObj[key] === smallerObj[key])) {
throw new Error("Duplicate field key '" + key + "'");
}
}
Object.assign(state.obj, partialState.obj);
}
export function finalize(state) {
return state.obj;
}
""";