Your current render_script_with() function is quite flexible and can handle a variety of SQL queries. However, if you have multiple recursive CTEs or multiple SELECT statements, you might want to modify it to accept arrays of parameters instead of individual parameters. This way, you can handle any number of CTEs or SELECT statements. You can use the example you provided from BQ documentation that use CTEs with the WITH clause.
CTEs are temporary result sets that can be referenced within another SQL statement, including SELECT, INSERT, UPDATE, or DELETE statements. They are useful for simplifying complex queries, breaking down large queries into smaller, more readable chunks, and performing multiple steps of data manipulation in a sequence.
In your examples, q1, q2, q3, q4, subQ1, and subQ2 are all CTEs. They are defined using the WITH clause and can be used in the subsequent SELECT statements.
However, please note that the scope of a CTE is only within the query where it is defined, and it cannot be referenced in subsequent queries. Also, if a CTE is defined inside a subquery, it can only be used in that subquery.
If you want to use these examples in your render_script_with() function, you would need to modify the function to accept an array of CTEs and an array of corresponding queries. Each CTE and query would be a string that contains the SQL code for that CTE or query. The function would then concatenate these strings to form the final SQL query.
Here’s an example of how you can modify your function to handle these examples:
function render_script_with(ctes, queries) {
let withClause = ‘’;
for (let i = 0; i < ctes.length; i++) {
withClause += ${ctes[i]} AS (${queries[i]}), ;
}
// Remove the trailing comma and space
withClause = withClause.slice(0, -2);
return WITH ${withClause};
}