The Alchemist Code Wiki

READ MORE

The Alchemist Code Wiki
The Alchemist Code Wiki

Documentation for this module may be created at Module:CargoUtil/doc

local util_vars = require('Module:VarsUtil')

local p = {}
local h = {}

function p.query(query)
	local tables = query.tables
	if type(tables) == 'table' then
		tables = table.concat(tables, ',')
	end
	local fields = query.fields
	if type(fields) == 'table' then
		fields = table.concat(fields, ',')
	end
	if type(query.join) == 'table' then
		query.join = table.concat(query.join, ',')
	end
	query.limit = query.limit or 9999
	if type(query.where) == 'table' then
		local arr = {}
		for _, v in pairs(query.where) do
			arr[#arr+1] = string.format('(%s)', v)
		end
		query.where = #arr > 0 and '('..table.concat(arr, ' AND ')..')' or nil
	end
	local rows = mw.ext.cargo.query(tables, fields, query)
	h.incrementQueryCounter()
	for i, row in ipairs(rows) do
		for k,v in pairs(row) do
			if v == '' then
				row[k] = nil
			end
		end
	end
	return rows
end

function p.rawquery(tables, fields, args)
	local rows = mw.ext.cargo.query(tables, fields, args)
	h.incrementQueryCounter()
	return rows
end

function p.store(values)
	local tbl = {''}
	for k,v in pairs(values) do
		if type(v) == 'boolean' then
			tbl[k] = v and 'Yes' or 'No'
		else
			tbl[k] = v
		end
	end
	return mw.getCurrentFrame():callParserFunction{
		name = '#cargo_store',
		args = tbl
	}
end

-- FOR DEBUG PURPOSES
local CARGO_QUERY_COUNT = 'cargo query count'

function p.count(frame)
	return mw.getCurrentFrame():callParserFunction('#var_final', CARGO_QUERY_COUNT)
end

function h.incrementQueryCounter()
	-- count the number of times "cargo_query" is called
	local val = util_vars.getVar(CARGO_QUERY_COUNT) or 0
	return util_vars.setVar(CARGO_QUERY_COUNT, val + 1)
end


return p