How to define get method in Anypoint studio if queryParam is defined? - api

Im trying to make a get method in Anypoint studio. I have already defined raml file with get method that looks something like this:
/kupci:
get:
queryParameters:
active:
required: false
enum:
- "true"
- "false"
I want to make a get flow that returns data from mysql database with 2 options:
if i have defined queryParam return everything from the database based of that condition
if not defined, just return everything from database

You just need a simple if else condition wherever you are creating your select query, and add a where clause if active is non empty.
SELECT field1, field2, ... FROM table
++ if(!isEmpty(attributes.queryParams.active)) 'WHERE active = $(attributes.queryParams.active)'
else ''
Note: You might need to change the above query if the datatype of the column active is Boolean. For example:
WHERE active IS $(attributes.queryParams.active)
You need to wrap this around the #[] script tag when writing in db:select as mentioned in the mule database connector docs

Related

Does gorm interpret the content of a struct with a logical OR?

New to SQL, I am writing as an exercise an API middleware that checks if the information contained in some headers match a database entry ("token-based authentication"). Database access is based on GORM.
To this, I have defined my ORM as follows:
type User struct {
ID uint
UserName string
Token string
}
In my middleware I retrieve the content of relevant headers and end up with the variables userHeader and tokenHeader. They are supposed to be matched to the database in order to do the authentication.
The user table has one single entry:
select * from users
// 1,admin,admintoken
The authentication code is
var auth User
res := db.Where(&User{UserName: userHeader, Token: tokenHeader}).Find(&auth)
if res.RowsAffected == 1 {
// authentication succeeded
}
When testing this, I end up with the following two incorrect results (other combinations are correct):
with only one header set to a correct value (and the other one not present) the authentication is successful (adding the other header with an incorrect value is OK (=auth fails))
no headers set → authentication goes though
I expected my query to mean (in the context of the incorrect results above)
select * from users where users.user_name = 'admin' and users.token = ''
select * from users where users.user_name = '' and users.token = ''
and this query is correct on the console, i.e. produces zero results (ran against the database).
The ORM one, however, seems to discard non-existing headers and assume they are fine (this is at least my understanding)
I also tried to chain the Where clauses via
db.Where(&User{UserName: userHeader}).Where(&User{Token: tokenHeader}).Find(&auth)
but the result is the same.
What should be the correct query?
The gorm.io documentation says the following on the use of structs in Where conditionals:
When querying with struct, GORM will only query with non-zero fields,
that means if your field’s value is 0, '', false or other zero
values, it won’t be used to build query conditions ...
The suggested solution to this is:
To include zero values in the query conditions, you can use a map,
which will include all key-values as query conditions ...
So, when the token header or both headers are empty, but you still want to include them in the WHERE clause of the generated query, you need to use a map instead of the struct as the argument to the Where method.
db.Where(map[string]interface{}{"user_name": userHeader, "token": tokenHeader}).Find(&auth)
You can use Debug() to check for the generated SQL (it gets printed into stderr); use it if you are unsure what SQL your code generates

API parameters - filter with ARRAY_CONTAINS (cosmos db back end)

I have an API I am pinging which queries a cosmos db to return records.
I can filter on a simple string in my api call like so:
// return objects where '_Subject' field equals "filterTest"
string getUrl = $"...baseApiPath/?$filter=_Subject+eq+'filterTest'";
This is working perfectly.
But I cannot figure out the filter syntax to make my API query be based on ARRAY_CONTAINS.
// return objects where '_Attachments' field CONTAINS "945afd138aasdf545a2d1";
How would I do that? Is there a general reference for API filter syntax somewhere?
If you're asking about how to query, a query against a property with an array of values looks like this:
SELECT * FROM c WHERE ARRAY_CONTAINS(c._Attachments, "945afd138aasdf545a2d1")
Another example in this answer.

error in google datastudio on using custom query

I am using a simple sql block of statements to execute and return a set of results in big query, This is working fine in big query and getting the results,I need to export this data to data studio, so in data studio i use bigquery as connector and select the project and custom query and in that I paste the contents below:
Declare metricType String;
SET metricType="compute.googleapis.com/instance/cpu/utilization";
BEGIN
IF (metricType="compute.googleapis.com/instance/cpu/usage_time")
THEN
SELECT m.value as InstanceName,metric.type as metricType,point.value.double_value as usagetime,point.interval.start_time as StartTime,point.interval.end_time as EndTime,h.value as instance_id FROM `myproject.metric_export.sd_metrics_export_fin`, unnest(resource.labels) as h,unnest(metric.labels) as m where metric.type='compute.googleapis.com/instance/cpu/usage_time' and h.key="project_id";
ELSE IF (metricType="compute.googleapis.com/instance/cpu/utilization")
THEN
SELECT m.value as InstanceName,metric.type as metricType,point.value.double_value as utilizationrate,point.interval.start_time as
StartTime,point.interval.end_time as EndTime,h.value as instance_id FROM `myproject-.metric_export.sd_metrics_export_fin`,unnest(resource.labels) as h,unnest(metric.labels) as m where metric.type='compute.googleapis.com/instance/cpu/utilization' and h.key="project_id";
END IF;
END IF;
END;
but after click "ADD" button i get the below error:
I am not sure what is this error about? I have not used any stored procedure and I am just pasting it as custom query.
Also If I try to save the results of the BigQuery into a view from the Bigquery console results pane, it gives me the error,
Syntax error: Unexpected keyword DECLARE at [1:1]
I am extremely new to datastudio and also to bigquery. Kindly Help thanks
First, I would like to make some considerations about your query. You are using Scripting in order to declare and create a loop within your query. However, since you declare and set the metricsType in the beginning of the query, it will never enter in the first IF. This happens because the value is set and it is not looping through anything.
I would suggest you to use CASE WHEN instead, as below:
SELECT m.value as InstanceName,metric.type as metricType,
CASE WHEN metric.type = #parameter THEN point.value.double_value ELSE 0 END AS usagetime,
CASE WHEN metric.type = #parameter THEN point.value.double_value ELSE 0 END AS utilizationrate,
point.interval.start_time as StartTime,point.interval.end_time as EndTime,h.value as instance_id
FROM `myproject.metric_export.sd_metrics_export_fin`, unnest(resource.labels) as h,unnest(metric.labels) as m
WHERE metric.type=#parameter and h.key="project_id";
Notice that I am using the concept of Parameterized queries. Also, for this reason this query won't work in the console. In addition, pay attention that whem you set the #parameter to "compute.googleapis.com/instance/cpu/utilization", it will have a non-null column with the usagetime and a null column named utilizationrate.
Secondly, in order to add a new data source in DataStudio, you can follow this tutorial from the documentation. After, selecting New Report, click on the BigQuery Connector > Custom Query> Write your Project id, you need to click in ADD PARAMETER (below the query editor). In the above query, I would add:
Name: parameter
Display name: parameter
Data type: text
Default value: leave it in blank
Check the box Allow "parameter" to be modified in reports. This means you will be able to use this parameter as a filter and modify its value within the reports.
Following all the steps above, the data source will be added smoothly.
Lastly, I must point that if your query ran in the Console you are able to save it as a view by clicking on Save view, such as described here.

How to convert SOQL query to SQL query?

I am working on SQL query, I have pre-created SOQL query, I am looking for a way to convert it to SQL query. The query is:
SELECT CronJobDetail.Name, Id, CreatedDate, State
FROM CronTrigger
WHERE CronjobDetail.JobType = 'bla bla'
AND CronJobDetail.Name LIKE '%bla bla2%'
But It does not run on terminal when I try to create monitoring script in Ruby. The error that I get:
(Got exception: INVALID_FIELD: No such relation 'CronJobDetail' on
entity 'CronTrigger'. If you are attempting to use a custom field, be
sure to append the '__c' after the custom field name. Please reference
your WSDL or the describe call for the appropriate names. in
/Users/gakdugan/.rvm/gems/ruby-1.9.3-p547/gems/restforce-2.2.0/lib/restforce/middleware/raise_error.rb:18:in
`on_complete'
Do you have any idea how can I fix it and make it run on SQL?
You are trying to access a relation without adding it to your FROM clause. Alternatively, if that's a custom field name, then do what the error message suggests you to do (add __c after the custom field name).
You probably want to do something like this:
SELECT CronJobDetail.Name, CronTrigger.Id, CronTrigger.CreatedDate, CronTrigger.State
FROM CronTrigger
INNER JOIN CronJobDetail ON CronJobDetail.id = CronTrigger.foreign_id // this you have to do yourself
WHERE CronjobDetail.JobType = 'bla bla'
AND CronJobDetail.Name LIKE '%bla bla2%'

How to get objects from worklight JSONStore where value of specific attribute attribute is null or empty

How can I get all the objects from JSONSTore where the value of specified attribute is null.
I have tried to specify the value of attribute as empty or null but not able to get the result.
I have to implement the below SQL query in IBM Worklight to get data from JSONStore.
select * from employee where age IS NULL
Make sure you have something like this in your search fields: {value: 'string'}.
Then add data like this: WL.JSONStore.get('collection').add({value: 'NULL'}).
Then search for it like this: WL.JSONStore.get('collection').find({value: 'NULL'}).
It is not currently possible to search for things that are not string, integer, number or boolean. Notice that 'NULL' is a string in my examples above.
Feature requests here.