Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New function to retrieve coltypes #4

Open
rousbound opened this issue Apr 22, 2024 · 0 comments
Open

New function to retrieve coltypes #4

rousbound opened this issue Apr 22, 2024 · 0 comments

Comments

@rousbound
Copy link

rousbound commented Apr 22, 2024

I stumbled across the need to use the getcoltypes and getcolnames from luasql and thought the following function could live on dado:

--------------------------------------------------------------------------------
-- Retrieves types and order of columns
-- @param self Dado Object.
-- @param columns String with fields list.
-- @param tabname String with table name.
-- @param cond String with where-clause (and following SQL text).
-- @param mode String indicating fetch mode (default == 'a').
-- @see dado.sql.select
-- @return Table with the entire result set.
function M.coltypes(self, columns, tabname, mode)
	mode = mode or "a"
	columns = columns or "*"
	local query = sql.select(columns, tabname, nil, "limit 1")
	local cur = self:cursor(query)
	local colorder = cur:getcolnames()
	local types = cur:getcoltypes()
	local t = {}
	if mode == "a" then
		for i,col in ipairs(colorder) do
			t[col] = types[i]
		end
	elseif mode == "n" then
		for i,col in ipairs(colorder) do
			t[i] = {
				col = v
			}
		end
	end
	return t
end

Use case:

local rs = conn:coltypes("*", "user", "a")
print(table.tostring(rs))
{
    id_user = "integer",
    admin = "bool"
    (...)
}

local rs = conn:coltypes("*", "user", "n")
print(table.tostring(rs))
{
   [1] = { col = "id", type ="integer" },
   [2] = { col = "admin", type = "bool" }
   (...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant