calculateShape()

The calculateShape() method allows a UDTF to dynamically determine its output shape (the column names and data types returned by the UDTF). This makes it possible to build very versatile functions that can alter their behavior based on the input values.

The standard nzlua table function is a good example of what can be done using the calculateShape() method since it allows a user to submit nzLua source code that is then used to process the data passed into the nzlua table function from the query. The code for the nzlua table function is included in the examples directory with the nzLua distribution.

A single argument is passed to the calculateShape() method that contains a Lua table. The contents of the Lua table are shown here.
args.count    The number of arguments
args[i].name       Name of the argument (not currently implemented)
args[i].type       nzLua datatype for the argument
args[i].length     The length of a char, varchar, nchar, or nvarchar
args[i].precision  The precision for a numeric
args[i].scale      The scale for a numeric
args[i].isconst    Boolean indicating if the argument is a constant
args[i].value      Value of the argument if it is a constant

The value of every constant argument is passed into the calculateShape() method. For non-constant arguments, only the data type and size is present. The calculateShape() method can then use the values of the constant arguments to determine the output columns and data types that the UDTF will return.

Example
function calculateShape(args)

if args[1].value < 1 or args[1].value > 1024 then error("Invalid number of output columns!", 0)
end

local shape={}
for i=1,args[1].value do
shape[i] = { "c" || i, varchar(100) }
end
return shape

end