Search code examples
kdb

KDB - run a function where the function name and parameters are passed in as a string


I am putting together a process that queries a KDB session and returns various bits of data to the front end. The front end passes a parameter to the KDB session which is a table name that comes in as a string – e.g. "table", where table is a table in the KDB session

I can run some simple KDB functions on the underlying table referred to, for example:

count `$"table"
cols `$"table"

In other circumstances, the front end passes a string to the KDB session which specifies a function and a parameter which, when run, returns a table equivalent to table above – e.g. "function parameter" I want to run the same simple functions on the table that is returned by running function parameter

The following do not return the output equivalent to count table and cols table respectively:

count `$"function parameter"
cols `$"function parameter"

What is the best way to get the count and cols from the table implied by the string "function parameter"

Many thanks!


Solution

  • In your example, cols is able to take either the table or the name of the table as a symbol as an argument, which is why it returns the column names as expected. count cannot take the name of the table as an argument so will return 1 since there is only a single symbol element.

    "function parameter" has been cast to a symbol `function parameter and there is no table with this name and so passing this as an argument to cols will throw an error, while passing this to count will return 1 for the same reasons as before.

    You might be interested in using the value function with a string argument and there is documentation on it here: http://code.kx.com/q/ref/metadata/#value.

    It will evaluate the string argument as if it had been typed into the command prompt. Using value "table" will return the table variable and value "function parameter" will run function with the parameter which will also a table.

    These can then be passed into your simple functions using count value "function parameter" or count value "table" to return the desired output.

    Hope this is useful,

    Mark