When pulling data from the database:
contacts = @db.query_all "SELECT name, age FROM contacts", as: {name: String, age: Int64}
We get as results:
Array(NamedTuple(name: String, age: Int64))
The problem is, i want to transfer this to a function:
Class X
def export(data_name : String, data : Array(NamedTupple(????)) )
hash = {
"xxxx" => { data_name => data }
}
return hash
end
end
As this data can be different namedTuples ( database information ), i can not keep passing the namedTuples definition for each call. It becomes a lot of redundant code.
Trying to make the namedTuples generic also does not work. Or to my understand, you need to make some code like
Class X ( T, Y )
def export(data_name : String, data : Array(T), data2 : Array(Y) )
hash = {
"xxxx" => { data_name => data, .... }
}
return hash
end
end
x = X((name: String, age: Int64), (address: String, number: Int64)).new
x.export("name", contacts, address)
It becomes a drag very fast when doing this for hundreds of queries… and updating several spots when one changes.
Maybe i am used too much PHP but it dull very fast to write such code, just to pass a array with data around. Other option is to “destory” the query result and rebuild it each time into a hash. But that is slow and pointless. It feels that the query_all, query_one are overly restrictive.
Anybody got a better or more flexible solution? Thanks.
Never mind … i am dumb.
contacts = @db.query_all "SELECT name, age FROM contacts", as: {String, String}
def export(data_name : String, data : Array(Tuple(String, String)) )
Solved it. Got my head stuck with the namedtuple so long.
Sigh … Well, that solved the error but simply moved the problem down the line again, as the DB gives a Int64 error ( i used a string ).
Better stop working at 03h at night.