Removing a column from result set in Groovy Sql rows - groovy

I have a query where I need to retrieve a column which I need only temporarily because I need to pass it in the parameter for a where clause, how can I remove this column and its value from my result set after it served that purpose. Hopefully the code will show what I mean...
def empQuery = "select id, name, address from Employee"
def retObj = [:]
def sql = new Sql(datasource)
retObj = sql.rows(empQuery.toString())
retObj.each {
def addressQuery = "select street from Address where employe_id = ${it['id']}
// at this point I want to remove 'id:n' from the result set hash map aka 'it'
}
Because later on I am displaying that result set on a page for the user, and the ID field is not relevant.
So can you please show the Groovy code to remove a column and its value from the rows data structure returned from sql.rows?

from http://docs.groovy-lang.org/latest/html/api/groovy/sql/GroovyRowResult.html
It looks like you can do something line:
retObj.each { it.remove('id')}
However I haven't tried it....

Related

Hybris Impex import based on PKs obtained from FlexQuery

What I want to achieve:
I want to set the value of two attributes, a1 and a2, to null for any product where a third attribute, a3, has a specific enum value.
What I have so far:
I have a flexquery which fetches a list of PKs for products which fulfill the requirement for a3. I now need to set the attributes of the products with those specific keys. The query is as follows:
SELECT {p.pk} FROM {Product AS p JOIN ProductOrigin AS o ON {o.pk} = {p.origin}} WHERE {o.code} = 'MARKETPLACE'
What I need help with:
I do not know how to combine the results of the flexquery with a typical impex operation. What I ideally want is to be able to simply pass the list of PKs to an INSERT_UPDATE as in:
INSERT_UPDATE Product; pk ; a1 ; a2 ;
queryResult; null; null;
I do not know if this is possible however. Even better would be if there is an even easier way to do this that I have not thought of.
Hi Erik you can achieve this even without using the Impex header and use groovy, steps are below.
Create groovy
#%impex.enableCodeExecution(true);
"#%groovy%
def queryCreditCardsToRemove = ''' SELECT {p.pk} FROM {Product AS p JOIN ProductOrigin AS o ON {o.pk} = {p.origin}} WHERE {o.code} = 'MARKETPLACE''''
def products = (Collection<ProductModel>)flexibleSearchService.search(queryCreditCardsToRemove).result
products.stream()
.each{
modelService
}
modelService.removeAll(cardsToRemove)
";
Save the file as impex
3.# Disable legacy scripting (makes groovy work at impex)
impex.legacy.scripting=false---> either you can change dynamically via hac-->configuration or add in local.properties
here is one beanshell script, execute it from hac -> console -> scripting languages!
In the below script, you need to put query that will give you result which is expected to you and on that result script will do further operations of saving null values to attributes!
import de.hybris.platform.servicelayer.search.FlexibleSearchService
import de.hybris.platform.servicelayer.search.SearchResult;
import de.hybris.platform.core.model.product.ProductModel
import de.hybris.platform.variants.model.VariantProductModel;
final Map<String, Object> params = new HashMap<String, Object>();
String query = "-------------- query to check condition of third (a3) attribute
with specific enum value ----------------------"
params = -----------if any need to be passed in query ------------------;
FlexibleSearchService fss = spring.getBean("flexibleSearchService")
final SearchResult<ProductModel> searchResult = fss.search(query, params);
for (final ProductModel product : searchResult.getResult()) {
// set attributes a1 and a2 to null
// save product model using modelService
}

User input not reflected in database (xampp)

In my program, I am getting the user input from combobox and inserting it to database. All values except 'classname' is getting reflected.Its value is shown as zero in the database. I am able to print all the values to be inserted before performing the SQL query.
This the function I executed.
def insert_staff():
id = entry_staffid.get()
subject = subject_combobox.get()
class_name = class_combobox.get()
class_time = timings_combobox.get()
print(id,subject,class_name,class_time)
staff = mysql.connector.connect(host="localhost", user="root", password="", database="school_database")
cursor_variable = staff.cursor()
query = "INSERT INTO staff_schedule(staff_id, subject_allotted, class_name, time_allotted) VALUES ('"+id+"','"+subject+"','"+ class_name +"','"+class_time+"')"
cursor_variable.execute(query)
staff.commit()
staff.close()
Can anyone tell why the value of 'classname' alone is not getting reflected?
Any help is greatly appreciated.
Initially I put the data type of class_name as INT but I was actually using VARCHAR values. This is the reason why the database reflected zero.

Android Studio Room query to get a random row of db and saving the rows 2nd column in variable

like the title mentions I want a Query that gets a random row of the existing database. After that I want to save the data which is in a specific column of that row in a variable for further purposes.
The query I have at the moment is as follows:
#Query("SELECT * FROM data_table ORDER BY RANDOM() LIMIT 1")
fun getRandomRow()
For now I am not sure if this query even works, but how would I go about writing my function to pass a specific column of that randomly selected row to a variable?
Ty for your advice, tips and/or solutions!
Your query is almost correct; however, you should specify a return type in the function signature. For example, if the records in the data_table table are mapped using a data class called DataEntry, then the query could read as shown below (note I've also added the suspend modifier so the query must be run using a coroutine):
#Query("SELECT * FROM data_table ORDER BY RANDOM() LIMIT 1")
suspend fun getRandomRow(): DataEntry?
If your application interacts with the database via a repository and view model (as described here: https://developer.android.com/topic/libraries/architecture/livedata) then the relevant methods would be along the lines of:
DataRepository
suspend fun findRandomEntry(): DataEntry? = dataEntryDao.getRandomRow()
DataViewModel
fun getRandomRecord() = viewModelScope.launch(Dispatchers.IO) {
val entry: DataEntry? = dataRepository.findRandomEntry()
entry?.let {
// You could assign a field of the DataEntry record to a variable here
// e.g. val name = entry.name
}
}
The above code uses the view model's coroutine scope to query the database via the repository and retrieve a random DataEntry record. Providing the returning DataEntry record is not null (i.e. your database contains data) then you could assign the fields of the DataEntry object to variables in the let block of the getRandomRecord() method.
As a final point, if it's only one field that you need, you could specify this in the database query. For example, imagine the DataEntry data class has a String field called name. You could retrieve this bit of information only and ignore the other fields by restructuring your query as follows:
#Query("SELECT name FROM data_table ORDER BY RANDOM() LIMIT 1")
suspend fun getRandomRow(): String?
If you go for the above option, remember to refactor your repository and view model to expect a String instead of a DataEntry object.

Use value from a column as paramater for json request and combine the table

I am using power query to load some json data in a table (matches). I want to use a specific part of that data (fixture_id) as a parameter for another json request in another query (predictions), and then combine that output in my main (matches) table. Anyone can point me in the right direction on how to do this ?
So here is my matches table:
And then in my fixtures table i can maybe i have:
apiKey = Excel.CurrentWorkbook(){[Name="ApiKey"]}[Content]{0}[Column1],
fixtureID = "?",
Source = Json.Document(Web.Contents("https://v2.api-football.com/predictions/" & fixtureID, [Headers=[#"X-RapidAPI-Key"=apiKey]])),
If i hardcode the fixtureID, i get this output:
But i want to calculate it dynamically, and then merge the output to the matches table.
The first step is to turn your request into a function that accepts parameters. Put your request on a new blank query:
let
fnGetData = (fixtureID as text) =>
let
apiKey = Excel.CurrentWorkbook(){[Name="ApiKey"]}[Content]{0}[Column1],
fixtureID = "?",
Source = Json.Document(Web.Contents("https://v2.api-football.com/predictions/"
& fixtureID, [Headers=[#"X-RapidAPI-Key"=apiKey]]))
in
Source
in
fnGetData
Rename it to fnGetData.
Then, go to your table and click on Add Column/Add Custom Function. Select fnGetData and the input parameter is your fixtureID column. This should make all the requests and you'll just have to expand the new column results.

Using string in place of property name (LINQ)

I have been able to get the values from tables using linq.
var q=(from app in context.Applicant
where app.ApplicantName=="")
Now what I want is this:
var q=(from app in context.Applicant
where app.stringIhave =="") // so instead of column name I have string which has same name as column.
Is it possible to specify string in Select as this is not sure what I will get in each case, I need different data all the time.
Is it possible to do so?
If no, then I will figure out something else.
Update
I have a GlobalString, which holds the column name of a table.
So when I query that table, I only specify from string which column value I want to get:
var q=(from app in context.Applicants
where app.ID==1013
select GlobalString //which is specifying that I want to get value from which column, as column name is not fixed.
//where GlobalString can have values like: app.FirstName..app.LastName etc
Update1:
var q = context.Applicants.Select("new(it.ApplicantFirstName as FirstName, it.ApplicantLastName as LastName)");
Error Message:
The query syntax is not valid. Near keyword 'AS'
You can use Dynamic Linq (available from NuGet) for that:
var q = context.Applicant.Where(app.stringIhave + " = #0", "");
for select you can try something like this
var q = context.Applicant.Select("new(it.FirstName as FirstName, it.LastName as LastName)");
so you only need construct string for that format

Resources