// I would prefer this to be delete.lua and load it using NSBundle
// But I failed. I don't know why.

static const char * deletelua = ""
"-- This script receives three parameters, all encoded with\n"
"-- MessagePack. The decoded values are used for deleting a model\n"
"-- instance in Redis and removing any reference to it in sets\n"
"-- (indices) and hashes (unique indices).\n"
"--\n"
"-- # model\n"
"--\n"
"-- Table with three attributes:\n"
"--    id (model instance id)\n"
"--    key (hash where the attributes will be saved)\n"
"--    name (model name)\n"
"--\n"
"-- # uniques\n"
"--\n"
"-- Fields and values to be removed from the unique indices.\n"
"--\n"
"-- # tracked\n"
"--\n"
"-- Keys that share the lifecycle of this model instance, that\n"
"-- should be removed as this object is deleted.\n"
"--\n"
"local model   = cmsgpack.unpack(ARGV[1])\n"
"local uniques = cmsgpack.unpack(ARGV[2])\n"
"local tracked = cmsgpack.unpack(ARGV[3])\n"
"\n"
"local function remove_indices(model)\n"
"	local memo = model.key .. \":_indices\"\n"
"	local existing = redis.call(\"SMEMBERS\", memo)\n"
"\n"
"	for _, key in ipairs(existing) do\n"
"		redis.call(\"SREM\", key, model.id)\n"
"		redis.call(\"SREM\", memo, key)\n"
"	end\n"
"end\n"
"\n"
"local function remove_uniques(model, uniques)\n"
"	local memo = model.key .. \":_uniques\"\n"
"\n"
"	for field, _ in pairs(uniques) do\n"
"		local key = model.name .. \":uniques:\" .. field\n"
"\n"
"       local field = redis.call(\"HGET\", memo, key)\n"
"		if field then\n"
"			redis.call(\"HDEL\", key, field)\n"
"		end\n"
"		redis.call(\"HDEL\", memo, key)\n"
"	end\n"
"end\n"
"\n"
"local function remove_tracked(model, tracked)\n"
"	for _, tracked_key in ipairs(tracked) do\n"
"		local key = model.key .. \":\" .. tracked_key\n"
"\n"
"		redis.call(\"DEL\", key)\n"
"	end\n"
"end\n"
"\n"
"local function delete(model)\n"
"	local keys = {\n"
"		model.key .. \":counters\",\n"
"		model.key .. \":_indices\",\n"
"		model.key .. \":_uniques\",\n"
"		model.key\n"
"	}\n"
"\n"
"	redis.call(\"SREM\", model.name .. \":all\", model.id)\n"
"	redis.call(\"DEL\", unpack(keys))\n"
"end\n"
"\n"
"remove_indices(model)\n"
"remove_uniques(model, uniques)\n"
"remove_tracked(model, tracked)\n"
"delete(model)\n"
"\n"
"return model.id\n";
