----------------------
-- sqlServer - SQL Server Module.
--
-- @module sqlServer

module(..., package.seeall)

local sqlServer = {}

sqlServer.makeConnectionData = function(datasource)
	local server = datasource.Server
	if datasource.Port then
		server = server .. "," .. datasource.Port
	end
	local connectionData = {
		{ Driver = "/usr/lib/inconcert_odbc/libmsodbcsql-17.so" },
		{ Server = server },
		{ Uid = datasource.User },
		{ Pwd = datasource.Pwd },
		{ Database = datasource.Name }
	}
	return connectionData
end

sqlServer.escapeValue = function(value)
	local dataType = type(value)
	if dataType == "string" then
		value = value:gsub("'", "''")
	end
	return value or ""
end

sqlServer.GetStringErr = function(err)
	--LogDebug("1--- sqlServer.GetStringErr")
	local dataType = type(t)
	if type(err) ~= "table" then
		return ""
	end
	local stringErr = ""
	for _,v in pairs(err) do
	--	LogDebug("   %s = %s", _, v)
		for _1, v1 in pairs(v) do
			LogDebug("     %s = %s", _1, v1)
		--	stringErr = stringErr .. (stringErr:len() > 0 and "\n" or "") .. (v1.message or "")
		end
		stringErr = stringErr .. (stringErr:len() > 0 and "\n" or "") .. (v.message or "")
	end
	--LogDebug("-- 2 sqlServer.GetStringErr    %s", stringErr)
	return stringErr
end

---------------------------------
-- EXEC el_nombre_del_sp '1', '2'
--
sqlServer.makeExecuteSPQuery = function(sp, parameters)
	assert(sp)
	assert(parameters)
	local query = ([[EXEC [%s] %s]]):format(sp, parameters)
	return query
end

SQLServer = {
	EscapeValue        = sqlServer.escapeValue,
	MakeConnectionData = sqlServer.makeConnectionData,
	GetStringErr       = sqlServer.GetStringErr,
	MakeExecuteSPQuery = sqlServer.makeExecuteSPQuery
}

function Init ()
	return SQLServer
end
