----------------------
-- mysql - MySQL Module.
--
-- @module mysql

module(..., package.seeall)

local mySql = mySql or {}

mySql.makeConnectionData = function(datasource)
	local connectionData = {
		{ Driver = "/usr/lib/inconcert_odbc/libmyodbc.so" },
		{ MULTI_HOST = 1 },
		{ Server = datasource.Server },
		{ Uid = datasource.User },
		{ Pwd = datasource.Pwd },
		{ Database = datasource.Name }
	}
	if datasource.Port then
		table.insert(connectionData, { Port = datasource.Port })
	end
	return connectionData
end

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

mySql.GetStringErr = function(err)
	--LogDebug("1--- mySql.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 mySql.GetStringErr    %s", stringErr)
	return stringErr
end

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

MySQL = {
	EscapeValue        = mySql.escapeValue,
	MakeConnectionData = mySql.makeConnectionData,
	GetStringErr       = mySql.GetStringErr,
	MakeExecuteSPQuery = mySql.makeExecuteSPQuery
}

function Init ()
	return MySQL
end
