The Alchemist Code Wiki

READ MORE

The Alchemist Code Wiki
Register
Advertisement

To edit the documentation or categories for this module, click here.


local util_vars = require('Module:VarsUtil')
local bool_to_str = {[true] = 'Yes', [false] = 'No'}

local p = {}
local h = {}

function p.queryAndCast(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

p.query = p.queryAndCast

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

function p.store(tbl)
	if CARGO_NAMESPACE and mw.title.getCurrentTitle().nsText ~= CARGO_NAMESPACE then
		return
	end
	if not tbl then return end
	local tbl2 = { '' }
	for k, v in pairs(tbl) do
		if type(v) == 'boolean' then
			tbl2[k] = bool_to_str[v]
		else
			tbl2[k] = v
		end
	end
	mw.getCurrentFrame():callParserFunction{
		name = '#cargo_store',
		args = tbl2
	}
	return
end

function p.setStoreNamespace(ns)
	CARGO_NAMESPACE = ns
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
Advertisement