Trying to execute a BiqQuery Stored Procedure from a Google Cloud Function - google-cloud-functions

I have the following code in Google Cloud Function. The cloud function is written in.NET 6 C#
var testsku = 1414;
var parameters = new BigQueryParameter[]
{
new BigQueryParameter("skuId", BigQueryDbType.Int64, testsku),
};
BigQueryClient client = BigQueryClient.Create(projectID);
string query = #"CALL 'xxxxxxx.xxxxxx.fraudskus'()";
BigQueryJob job = client.CreateQueryJob(
sql: query,
parameters: parameters,
options: new QueryOptions { UseQueryCache = false });
// Wait for the job to complete.
job.PollUntilCompleted();
// Display the results
int numOrders = 0;
foreach (BigQueryRow row in client.GetQueryResults(job.Reference))
{
numOrders++;
}
message = "Num of rows = " + numOrders;
The stored procedure runs fine in BIGQUERY and outputs the right results, but I am getting errors on the call to the stored procedure as follows.
"The service bigquery has thrown an exception.
No HttpStatusCode was specified.
Google.Apis.Requests.RequestError
Job unique-moon-366800/US/job_24e29215_e011_4d66_a2c4_bbf5640d5cc6 contained 2 error(s). First error message: Syntax error: Unexpected string literal 'unique-moon-366800.ecommerce_fraud_ds.fraudskus' at [1:6] [0]
Errors [
Message[Syntax error: Unexpected string literal 'xxxx.xxxxx.fraudskus' at [1:6]] Location[query - ] Reason[invalidQuery] Domain[]
Message[Syntax error: Unexpected string literal 'xxxx.xxxxx.fraudskus' at [1:6]] Location[query - ] Reason[invalidQuery] Domain[]
]
Google.GoogleApiException: The service bigquery has thrown an exception. No HttpStatusCode was specified. Job xxxxxxx/US/job_24e29215_e011_4d66_a2c4_bbf5640d5cc6 contained 2 error(s). First error message: Syntax error: Unexpected string literal 'unique-moon-366800.ecommerce_fraud_ds.fraudskus' at [1:6]
at Google.Cloud.BigQuery.V2.BigQueryJob.ThrowOnFatalError()
at Google.Cloud.BigQuery.V2.BigQueryJob.GetQueryDestinationTable()
at Google.Cloud.BigQuery.V2.BigQueryJob.GetQueryResults(GetQueryResultsOptions options)
at Google.Cloud.BigQuery.V2.BigQueryClientImpl.GetQueryResults(JobReference jobReference, GetQueryResultsOptions options)
at SimpleHttpFunction.Function.HandleAsync(HttpContext context) in /workspace/Function.cs:line 196
at Google.Cloud.Functions.Hosting.HostingInternals.Execute(HttpContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)"
I can get the results I expect if I use sql SELECT, but not if I try to call the stored procedure.

Related

String passed to JSON library turns into a table

When I execute this code (Windows 10) i get an error from within the library.
local json = loadfile("json.lua")()
local handle = io.popen("curl \"https://someurl.com\"")
local result = handle:read("*all")
handle:close()
local output = json:decode(result)
The error in the console:
lua: json.lua:377: expected argument of type string, got table
stack traceback:
[C]: in function 'error'
json.lua:377: in method 'decode'
monitor.lua:10: in main chunk
[C]: in ?
I'm running the code on Windows 10 with a console and using this library: https://github.com/rxi/json.lua
This function always returns the same error, even if I try different types of arguments, i.e. numbers or strings.
function json.decode(str)
if type(str) ~= "string" then
error("expected argument of type string, got " .. type(str))
end
local res, idx = parse(str, next_char(str, 1, space_chars, true))
idx = next_char(str, idx, space_chars, true)
if idx <= #str then
decode_error(str, idx, "trailing garbage")
end
return res
end
local output = json:decode(result)
is syntactic sugar for
local output = json.decode(json, result)
json is a table.
Hence inside function json.decode the following if statement is entered:
if type(str) ~= "string" then
error("expected argument of type string, got " .. type(str))
end
which produces the observed error.
To fix this you can either change the function definiton to
function json:decode(str)
-- code
end
Or you call
local output = json.decode(result)
You should pick the second one as changing the json library will affect code that already uses json.decode as intended by the author.

How to fix the error 'API call to bigquery.jobs.query failed with error: Encountered " "FROM" "from "" at .... Was expecting: ")"'

I am trying to run a bigquery api call using the query string(attached in the code) from appscript; The query runs perfectly fine in bigquery UI
I have tried the following with no success:
1. include parentheses in orders.creation_date in the query string
2. replace orders with the actual table table i.e [my-project:theservices.theservice_order_item]
/**
* Runs a BigQuery query and logs the results in a spreadsheet.
*/
function runQuery() {
var projectId = 'my-project';
var request = {
query:
"SELECT extract(date from orders.creation_date) as the_date \n FROM [my-project:theservices.theservice_order_item] AS orders LIMIT 10;"
};
};
Following is the error I get:
API call to bigquery.jobs.query failed with error: Encountered " "FROM" "from "" at line 1, column 22. Was expecting: ")" ... (line 23, file "Code")
Quoting App Script BigQuery Standard SQL insert or update statement:
You need to set the useLegacySql flag/parameter to false, to indicate that you want to use standard SQL, like so:
var job = {
configuration: {
query: {
query: 'SELECT ....',
useLegacySql: false
}
Additionally, when a table looks like this - that's #legacySQL:
FROM [my-project:theservices.theservice_order_item]
In #standardSQL the table should be enclosed in tilde '`' and has a '.' between the project and dataset name:
FROM `my-project.theservices.theservice_order_item`

postgres json parameter to a function

CREATE OR REPLACE FUNCTION public.writecalculations(id integer, times integer, j json)
RETURNS text
LANGUAGE plv8
AS
$body$
var overallStart = new Date();
var result = 0;
var insertStmt = "Insert into \"CalculationResult\" Values($1,$2,$3::json)"
result += plv8.execute(insertStmt,[id, times, j]);
var loopEnd = new Date();
return JSON.stringify({"AffectedRows": result, "OverallRuntime": loopEnd-overallStart}) ;
$body$
IMMUTABLE STRICT
COST 100;
COMMIT;
This gives an error when executed using
WbCall calculationResult(4,4,'{\"a\":1}');
Error :
An error occurred when executing the SQL command:
ERROR: function calculationresult(integer, integer, unknown) does not exist
Hint: No function matches the given name and argument types. You might need >to add explicit type casts.
Position: 15 [SQL State=42883]
What am I doing wrong?
I tried various options of passing text with "" and '' and also as passing json
try:
WbCall calculationResult(4,4,'{"a":1}'::json);
calculationresult(integer, integer, unknown) - PostgreSQL didn't detect type of '{"a":1}', so it ask you to add explicit type casts.

Using Google Apps Script how to only retrieve objects from ScriptDb which possess property/key

Is it possible to query ScriptDb to return only those objects which possess a specific property/key?
results = db.query({key: db.not(null)}); // always triggers error "We're sorry, a server error occurred. Please wait a bit and try again."
results = db.query({key: db.not(undefined)}); // returns all objects in the database
and the reverse:
results = db.query({key: undefined});
results = db.query({key: null}); // both these cause an error on any of the ScriptDbResult methods "Your query object contains an invalid component."
Any thoughts?

Parameter index out of range when trying to retrieve the return value of a stored function

I have a function that takes a few parameters and is generating a unique varchar id to be returned to the application. When I call the function from my java application it executes (the data is inserted), but when I try to retrieve the outparam it throws SQL exception
Parameter index out of range (1 > number of parameters, which is 0).
java code:
String sql = "{?=call mytable.myFunction (?,?,?,?,?)}";
CallableStatement tmt = sqlConn.prepareCall(sql);
tmt.registerOutParameter(1, Types.VARCHAR);
tmt.setString(2, firstName);
tmt.setString(3, lastName);
tmt.setDate(4, new java.sql.Date(dob.getTime()));
tmt.setString(5, null);
tmt.setString(6, null);
tmt.execute();
String accountNumber = tmt.getString(1);
I'm using Navicat to work with MySQL, and the procedure executes in Navicat and shows the correct return value. However, when I call tmt.getString(1) from java app, it throws the above exception.
Please, help.
Thank you.