I have a service that runs parametrized GBQ query with some values sent by user. In case if user didn't sent values it should run the query without filtering.
Here is a code snippet that builds query params:
const params = {
someIds: this.someIds,
someNames : this.userInput.someNames ? this.userInput.someNames : [],
};
If userInput.someNames contains values, query runs as expected. But when it gets an empty array as a parameter, GBQ throws an error:
Cannot read properties of undefined (reading 'length')
Here is a query snippets that I've tried - none of them worked, same error each time the array is empty:
SELECT
some_id,
some_name,
date_time,
RANK() OVER (PARTITION BY some_name, date_time ORDER BY some_field_name DESC) AS ranked,
some_field_name
FROM
db_name.table_name
WHERE
some_id IN UNNEST ( @someIds )
AND ((ARRAY_LENGTH(@someNames ) IS NULL
OR ARRAY_LENGTH(@someNames ) = 0)
OR @someNames IS NULL
OR some_name IN UNNEST(@someNames ))
SELECT
some_id,
some_name,
date_time,
RANK() OVER (PARTITION BY some_name, date_time ORDER BY some_field_name DESC) AS ranked,
some_field_name
FROM
db_name.table_name
WHERE
some_id IN UNNEST ( @someIds )
AND
CASE
WHEN @someNames IS NULL THEN TRUE
WHEN ARRAY_LENGTH(@someNames ) = 0 THEN TRUE
ELSE some_name IN UNNEST(@someNames)
END
I also tried to pass the null instead of empty array and it didn't work. How to fix this issue?
Solved issue by adding optional 'type' parameter to the query options
const options = {
query,
location: 'US',
params,
types: {
someNames :['string']
}, //use this for empty arrays identification
};