[Solved] NamedTuple issue

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. :rofl:

   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. :confounded:


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.

Is export just a method? What happens next? What do you do with that hash?

I don’t know if you know this, but you don’t need to specify the type of method arguments, they are optional. So you could simply define export as:

def export(data_name : String, data)
  {"xxxx" =>  { data_name => data } }
end
1 Like

I don’t know if you know this, but you don’t need to specify the type of method arguments, they are optional.

/hits head against wall…

Seem i got stuck in naming my methods so much with Go, that it did not even dawn on me that you can do without in Crystal.

Thanks Asterite.

1 Like