Ruby SQlite SELECT Returning an Unwanted Array - sql

I am trying to grab a couple values from an sqlite database, but instead of returning the value I am SELECT-ing, it is returning that value in an array inside of another array.
My code:
def self.find(id, database_connection)
name = database_connection.execute("SELECT name FROM pokemon WHERE id = ?", id)
type = database_connection.execute("SELECT type FROM pokemon WHERE id = ?", id)
pokemon_inst = Pokemon.new(id: id, name: name, type: type, db: database_connection)
end
The Problem:
When I run pry.binding
name outputs [["Pikachu"]]
type outputs [["electric]]
Is this working correctly? I can't imagine I should I just be calling name[0][0] to access the data, right?

The execute() method wraps everything it is returning in an array, and each database row is placed in an array. So, for the single value being queried to be in two arrays is correct.
Since everything is working as it should I will be adjusting my code to this:
def self.find(id, database_connection)
pokemon = database_connection.execute("SELECT * FROM pokemon WHERE id = ?", id).flatten
name = pokemon[1]
type = pokemon[2]
pokemon_inst = Pokemon.new(id: id, name: name, type: type, db: database_connection)
end
The adjustments are to flatten the array when it is assigned the queried data and to assign the individual values from that array.

Related

How to retrieve the list of dynamic nested keys of BigQuery nested records

My ELT tools imports my data in bigquery and generates/extends automatically the schema for dynamic nested keys (in the schema below, under properties)
It looks like this
How can I get the list of nested keys of a repeated record ? so for example I can group by properties when those items have said property non-null ?
I have tried
select column_name
from my_schema.INFORMATION_SCHEMA.COLUMNS
where
table_name = 'my_table
But it will only list first level keys
From the picture above, I want, as a first step, a SQL query that returns
message
user_id
seeker
liker_id
rateable_id
rateable_type
from_organization
likeable_type
company
existing_attempt
...
My real goal through, is to group/count my data based on a non-null value of a 2nd level nested properties properties.filters.[filter_type]
The schema may evolve when our application adds more filters, so this need to be dynamically generated, I can't just hard-code the list of nested keys.
Note: this is very similar to this question How to extract all the keys in a JSON object with BigQuery but in my case my data is already in a shcema and it's not a JSON object
EDIT:
Suppose I have a list of such records with nested properties, how do I write a SQL query that adds a field "enabled_filters" which aggregates, for each item, the list of properties for wihch said property is not null ?
Example input (properties.x are dynamic and not known by the programmer)
search_id
properties.filters.school
properties.filters.type
1
MIT
master
2
Princetown
null
3
null
master
Example output
search_id
enabled_filters
1
["school", "type"]
2
["school"]
3
["type"]
Have you looked at COLUMN_FIELD_PATHS? It should give you the paths for all columns.
select field_path from my_schema.INFORMATION_SCHEMA.COLUMN_FIELD_PATHS where table_name = '<table>'
[https://cloud.google.com/bigquery/docs/information-schema-column-field-paths]
The field properties is not nested by array only by structures. Then a UDF in JavaScript to parse thise field should work fast enough.
CREATE TEMP FUNCTION jsonObjectKeys(input STRING, shownull BOOL,fullname Bool)
RETURNS Array<String>
LANGUAGE js AS """
function test(input,old){
var out=[]
for(let x in input){
let te=input[x];
out=out.concat(te==null ? (shownull?[x+'==null']:[]) : typeof te=='object' ? test(te,old+x+'.') : [fullname ? old+x : x] );
}
return out;
Object.keys(JSON.parse(input));
}
return test(JSON.parse(input),"");
""";
with tbl as (select struct(1 as alpha,struct(2 as x, 3 as y,[1,2,3] as z ) as B) A from unnest(generate_array(1,10*1))
union all select struct(null,struct(null,1,[999])) )
select *,
TO_JSON_STRING (A ) as string_output,
jsonObjectKeys(TO_JSON_STRING (A),true,false) as output1,
jsonObjectKeys(TO_JSON_STRING (A),false,true) as output2,
concat('["', array_to_string(jsonObjectKeys(TO_JSON_STRING (A),false,true),'","' ) ,'"]') as output_sring,
jsonObjectKeys(TO_JSON_STRING (A.B),false,true) as outpu
from tbl

ITXEX field cleared when HR_INFOTYPE_OPERATION is called

We got into difficulties in maintaining the ITXEX field (Long text indication) of an Infotype record.
Say we got an existing record in an Infotype database table with a long text filled (ITXEX field value in that record is set to 'X').
Some process updates the record through HR_CONTROL_INFTY_OPERATION like this:
CALL FUNCTION 'HR_CONTROL_INFTY_OPERATION'
EXPORTING
infty = '0081'
number = '12345678'
subtype = '01'
validityend = '31.12.9999'
validitybegin = '19.05.2019'
record = ls_0081 " ( ITXEX = 'X' )
operation = 'MOD'
tclas = 'A'
nocommit = abap_true
IMPORTING
return = ls_return.
This call does update the record but clearing it's ITXEX field.
It's important to say that making the same action through PA30 does update the record and maintain ITXEX field as it was.
The described problem seems similar to that question. Trying the solutions given there didn't solve the problem.
Why the two approaches (PA30 and function module) don't work the same? How to fix this?
First of all, FM parameters you use are incorrect. How do you want the infotype to be updated if you set nocommit = TRUE?
Also, you are missing the correct sequence which must be used for the update procedure:
Lock the Employee
Read the infotype
Update the infotype
Unlock the Employee
The correct snippet for your task would be
DATA: ls_return TYPE bapireturn1.
DATA: l_infty_tab TYPE TABLE OF p0002.
CALL FUNCTION 'HR_READ_INFOTYPE'
EXPORTING
pernr = '00000302'
infty = '0002'
TABLES
infty_tab = l_infty_tab.
READ TABLE l_infty_tab ASSIGNING FIELD-SYMBOL(<infotype>) INDEX 1.
<infotype>-midnm = 'Shicklgruber'. " updating the field of infotype
CALL FUNCTION 'ENQUEUE_EPPRELE'
EXPORTING
pernr = '00000302'
infty = '0002'.
CALL FUNCTION 'HR_CONTROL_INFTY_OPERATION'
EXPORTING
infty = <infotype>-infty
number = <infotype>-pernr
subtype = <infotype>-subty
validityend = <infotype>-endda
validitybegin = <infotype>-begda
record = <infotype>
operation = 'MOD'
tclas = 'A'
IMPORTING
return = ls_return.
CALL FUNCTION 'DEQUEUE_EPPRELE'
EXPORTING
pernr = '00000302'
infty = '0002'.
This way itxex field is treated correctly and if existed on that record, will remain intact. However, this method will not work for updating the long text itself, for that you must use object-oriented way, methods of class CL_HRPA_INFOTYPE_CONTAINER.

Sql query not working on matlab properly

So i'm working on a laravel project where i pass some data to matlab and then matlab will edit them..everything works fine except the function of matlab that i wrote..
function show(a)
econ=database('datamining','root','');
curs=exec(con,'SELECT name FROM dataset_choices WHERE id = a');
curs = fetch(curs);
curs.Data
end
i want this function to display the name of the dataset the user choose..the problem is that it doesnt work writing just where id = a... but if i write for example where id=1 it works..
i tried to display just the a with disp(a) to see what is the value of the a and it is store the right id that user had choose..so how can i use it in my query??
Try:
a = num2str(a); % or make sure the user inputs a string instead
curs=exec(con,['SELECT name FROM dataset_choices WHERE id = ',a]);
If a = '1', then the brackets would print:
'SELECT name FROM dataset_choices WHERE id = 1'

CDE: multiple select

I am trying to create a dashboard that consist from two components: CCC Bar chart and Multiple select component.
I use the multiply select component for assignment param value, which is using in the datasource. (MDX query):
SELECT
NON EMPTY {[Measures].[doc_count]} ON COLUMNS,
NON EMPTY {[Dimension Usage date_publish.Hierarchy date_publish].[date_publish].Members} ON ROWS
FROM [Docs]
WHERE CrossJoin({${param_hosts}}, {[event].[active]})
So if I set (multiply select component) property value array with pairs:
( {arg:[host].[news.com] value:news.com}, {{arg:[host].[somesite.com] value:somesite.com}} ), everything work perfect.
The parameter is bound to the component receives the correct value, for example: [host]. [News.com], [host]. [Somesite.com].
But if I try to fill the multiply select component from the datasource it become unworkable.
As DataSource, I use the sql over sqlJndi with query: SELECT distinct (host) as Id, concat ('[host]. [', Host, ']') as Value FROM docs_fact where dim_event_id = 1;
The result this query is a table:
id value
news.com | [host].[news.com]
somesite.com | [host].[somesite.com]
Parameter is assigned a value: news.com, somesite.com
Changing the properties of the Value as id only affects which of the fields (id or value) will be shown to the user, and the parameter's value is not affected.
Tell me please, is it possible to specify which of the columns to be used for display to the user and which of the columns to be used to generate results?
No, but you can change the dataset on the clientside using the postFetch function on the multi-select component.
function (dataset) {
for (var i=0; i < dataset.resultset.length; i++) {
var temp = dataset.resultset[i][0];
dataset.resultset[i][0] = dataset.resultset[i][1];
dataset.resultset[i][1] = temp;
}
return dataset;
}
Or similar

How to get the Database Id from an XML Id

The osv.osv provides a get_xml_id method to find the XML Id for the provided Database Id.
What is the best way to do the opposite?
Knowing the XML Id (it was defined in the data loading file), how can I get the corresponding Database Id, so that I can refer to it in tour Python code?
The ir.model.data model also has a get_object() method returning a browsable record given a model name and an xml_id.
So, another solution could be:
m = self.pool.get('ir.model.data')
id = m.get_object(cr, uid, 'base', 'user_root').id
The ir_model_data object has a _get_id() method that does what you're looking for. You can see it in use in the res_users._get_admin_id() method:
def _get_admin_id(self, cr):
if self.__admin_ids.get(cr.dbname) is None:
ir_model_data_obj = self.pool.get('ir.model.data')
mdid = ir_model_data_obj._get_id(cr, 1, 'base', 'user_root')
self.__admin_ids[cr.dbname] = ir_model_data_obj.read(cr, 1, [mdid], ['res_id'])[0]['res_id']
return self.__admin_ids[cr.dbname]