Google App Script Big Query - GoogleJsonResponseException: API call to bigquery.jobs.query failed with error: Query parameter 'X' not found - sql

I have been struggling with this for a couple of days now and I felt like I should reach out. This might be very simple but I am not from a programming background and I haven't found any resources to solve this so far.
Basically, I want to parameterize a SQL query that is running for BigQuery within Google APp Script, it takes a variable from a user from a Google From they have submitted and I wanted to ensure that this won't be injectable by parameterizing the query, however, I got the following error that I could not fix:
GoogleJsonResponseException: API call to bigquery.jobs.query failed with error: Query parameter 'account_name' not found at [1:90]
Here is how I run the query:
//Query
const sqlQuery = 'SELECT district FROM `table` WHERE account_name = #account_name AND ent_theatre=("X") LIMIT 1;'
const request = {
query: sqlQuery,
params: { account_name: queryvar },
useLegacySql: false,
};
// Run Query
var queryResult = BigQuery.Jobs.query(request,projectID);
I have created the query based on Google's documentation

Your syntax for request object is not correct. The right syntax for the BigQuery.Jobs.query Request is like below:
const request = {
query: sqlQuery,
queryParameters: [
{
name: "account_name",
parameterType: { type: "STRING" },
parameterValue: { value: queryvar }
}
],
useLegacySql: false,
};
For more detail about QueryRequest Object refer to this link.

Related

fetching countriesInShippingZones

I'm trying to fetch the countries that I can ship to with shopify-buy.
as client.shop.fetchInfo() doesn't return that information I build my own query with the unoptimized version of the SDK to fetch the store information.
But any query with countriesInShippingZones always returns the error "Error: No field of name "countriesInShippingZones" found on type "Shop" in schema" (without that, it works)
here is an example of my query:
props.client.graphQLClient.query((root) => {
root.add("shop", {}, (shop) => {
shop.add("name");
shop.add("currencyCode");
shop.add("countriesInShippingZones");
});
});

Get Article list by subscription

I am trying to make a filter with which I could get subscription records
Entity 'Subscription'
export class Subscription {
#PrimaryColumn()
id: string;
#Column('uuid')
userId: string;
#Column('uuid')
targetUserId: string;
#CreateDateColumn()
createdAt: Date;
}
Filter
applyFilter(query: QueryArticle, qb: SelectQueryBuilder<Article>, userId?: string) {
if (query.filter) {
switch (query.filter) {
....
case 'subscriptions':
qb.select(
`article.authorId WHERE targetUserId IN (SELECT targetUserId FROM Subscription WHERE userId=${userId})`,
);
break;
}
}
return qb;
}
SQL code
Select * FROM article WHERE authorId=targetUserId IN (SELECT targetUserId FROM Subscription WHERE userId=userId)
Error
syntax error at or near "f5779e5" +3974ms
QueryFailedError: syntax error at or near "f5779e5"
How can I get all the posts of people followed by a person use TypeORM?
Thanks in advance for your answer!
DO NOT DO WHAT YOU ARE DOING. You are risking a SQL Injection. If you really want to do a manual query, you can do manager.query:
const output = manager.query('article."authorId" WHERE "targetUserId" IN (SELECT "targetUserId" FROM Subscription WHERE "userId" = :userId)',
{ userId: userId }
);
Notice the second parameter that contains parameters which is referenced by key with :userId. If you're using template strings for queries, you're probably doing something wrong.
If you want to use the QueryBuilder, then it's going to look a little different (more info on QueryBuilder here)
const output = articleRepo.createQueryBuilder('article')
.select('article.authorId')
.where('article."authorId" IN (SELECT "targetUserId" FROM subscription WHERE "userId" = :userId)',
{ userId: userId }
)
.getRawMany(); // If you remove the .select('article.authorId'), you can use .getMany()

How to avoid Big Query nesting date values in JSON?

I'm using Standard SQL with Big Query and everything is working fine, except my dates are in a nested structure and I have no idea why Big Query is doing that.
Here's my query:
SELECT
DATETIME(salesData.date_utc, "EST") AS DateEST,
salesData.serial_no AS MachineID
FROM
sales.sales_all AS salesData
WHERE salesData.date_utc > "2018-05-26T05:00:00" AND salesData.date_utc
< "2018-05-27T04:59:59"
ORDER BY salesData.date_utc DESC
When I'm downloading the results as JSON it's all fine:
{"DateEST":"2018-05-26T23:57:58","MachineID":"1708FB0000009-B"}
{"DateEST":"2018-05-26T23:52:07","MachineID":"1710FB0000034-B"}
But if I'm using Google Cloud Functions and pull the data, it results in a nested JSON.
[
{
"DateEST": {
"value": "2018-05-26T23:57:58"
},
"MachineID": "1708FB0000009-B"
}, ...
Here's part of my Cloud Function code:
const options = {
query: sqlQuery,
useLegacySql: false, // Use standard SQL syntax for queries.
};
bigquery
.query(options)
.then(results => {
const rows = results[0];
response.json(rows);
})
.catch(err => {
console.error('ERROR:', err);
response.send(500);
});
This issue was solved by casting the DATETIME object as a string:
CAST(DATETIME(salesData.date_utc, "EST") as STRING) as DateEST

How to use query parameter as col name on sequelize query

So, I have an Express server running Sequelize ORM. Client will answer some questions with radio button options, and the answers is passed as query parameters to the URL, so I can make a GET request to server.
The thing is: my req.query values are supposed to be the column names for my database table. I want to know if it's possible to get the response from the database using Sequelize, and passing the parameters as the column name of the table.
async indexAbrigo(req, res) {
try {
let abrigos = null
let type = req.query.type // type = 'periodoTEMPORARIO'
let reason = req.query.reason // reason = 'motivoRUA'
abrigos = await Abrigos.findAll({
attributes: ['idABRIGOS'],
where: {
//I want type and reason to be the parameters that I got from client
type: 'S',
reason: 'S'
}
})
}
res.send(abrigos)
}
This is not working, the result of the query is something like
(SELECT `idABRIGOS` FROM Abrigos WHERE `type` = `S` AND `reason` = `S`)
Instead, I need that type and reason get translated to their values, and these values will be passed to the SQL. Is it possible to do with Sequelize? Or is it even possible with any ORM for Node/Express?
Thanks.
Yes, you can do it with computed property names. It would look like this:
where: {
[type]: 'S',
[reason]: 'S'
}
Your node.js version must be compatible with ES6.
Thank you - I am passing parameters right from req.body and this worked perfectly for me so I am posting it in the event that it may save someone time.
app.post('/doFind', (req, res) => {
Abrigos.findAll(
{[req.body.field]: req.body.newVal},
{returning: true, where: {id: req.body.id}}
)
.then( () => {
res.status(200).end()
})
.catch(err => {
console.log("Err: " + err)
res.status(404).send('Error attempting to update database').end()
})
})

Is there a specific scope that I can use WL.Server.SetActiveUser?

I am trying to create an adapter based authentication in Worklight. I have added my Realm, Security test, and Login Module to the authenticationConfig file. I have tried to follow along with the modules provided by IBM. I've copied the exact syntax and even hard coded values for the WL.Server.setActiveUser method. But I continue to get an error. Is there a certain scope I can use this method in? Does anyone see or know where my error is?
I continue to get the follow error:
LOG: Request [login]
LOG: Request [/apps/services/api/GPC2/android/query]
LOG: response [/apps/services/api/GPC2/android/query] success: /*-secure-
{"responseID":"1","isSuccessful":true,"resultSet REMOVED LINE THAT CONTAINED DB RESULTS FOR SECURITY
[/apps/services/api/GPC2/android/query] exception.
SCRIPT5007: Unable to get value of the property 'setActiveUser': object is null or undefined
var lname= responseData.invocationResult.resultSet[0].somelastname;
var gpcid = responseData.invocationResult.resultSet[0].someid;
var fname = responseData.invocationResult.resultSet[0].somefname;
WL.Logger.debug("Login :: SUCCESS" + lname + " " + gpcid + " " + fname); //this line does write the values to the log
//WL.Client.login("NotificationsRealm");
WL.Server.setActiveUser ("NotificationsRealm", {
userId: gpcid,
displayName: fname,
attributes: {
firstName: fname,
lastName : lname,
isUserAuthenticated: 1,
}
});
Looking at the API documentation for WL.Server.setActiveUser, it should be like this:
WL.Server.setActiveUser ("ACMERealm", {
userId: "38017840288",
displayName: "John Doe",
attributes: {
"firstName": "John",
"lastName": "Doe",
"lastLogin": "2010-07-13 19:25:08.0 GMT",
}
})
Looks like you are missing the double quotes for the attributes?