This patch adds two new configure option;

sql = {
    state_table = "custom_state";
    archive_table = "custom_archive";
}

This is needed for custom database applications. Without this users need to
create postgres views and get exceedingly slow performance with this error

Index "prosody_unique_index" does not exist, performance may be worse than
normal!

With this users can skip views and prosody_unique_index, this patch looks
for custom_state_unique_index instead and skips the need for views, lua's
JIT ensures the result is exactly as fast.

This patch still requires the exact same table schema, it only allows users
to override table names "prosody" and "prosodyarchive" but will still
default to these so users who don't need this will be unaffected.

-- 
You received this message because you are subscribed to the Google Groups 
"prosody-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/prosody-dev/CAHhipD_qmvHs8Ok%2BBzPyMOQawr4P4koP61sG%3DaiyzHROzFyYzw%40mail.gmail.com.
# HG changeset patch
# User Arc Riley <[email protected]>
# Date 1794280404 28800
#      Mon Nov 09 19:13:24 2026 -0800
# Node ID 86d9795a6842f32a23cd4078a9338038cd359681
# Parent  68c7b416d9b053157e0b812599415dcd5c96e331
Adding support for configuring sql state_table and archive_table

diff -r 68c7b416d9b0 -r 86d9795a6842 plugins/mod_storage_sql.lua
--- a/plugins/mod_storage_sql.lua	Mon Nov 09 16:48:06 2026 +0000
+++ b/plugins/mod_storage_sql.lua	Mon Nov 09 19:13:24 2026 -0800
@@ -96,11 +96,11 @@
 local function keyval_store_get(user, store)
 	local haveany;
 	local result = {};
-	local select_sql = [[
+	local select_sql = ([[
 	SELECT "key","type","value"
-	FROM "prosody"
+	FROM "%s"
 	WHERE "host"=? AND "user"=? AND "store"=?;
-	]]
+	]]):format(engine.params.state_table);
 	for row in engine:select(select_sql, host, user or "", store) do
 		haveany = true;
 		local k = row[1];
@@ -119,17 +119,17 @@
 	end
 end
 local function keyval_store_set(data, user, store)
-	local delete_sql = [[
-	DELETE FROM "prosody"
+	local delete_sql = ([[
+	DELETE FROM "%s"
 	WHERE "host"=? AND "user"=? AND "store"=?
-	]];
+	]]):format(engine.params.state_table);
 	engine:delete(delete_sql, host, user or "", store);
 
-	local insert_sql = [[
-	INSERT INTO "prosody"
+	local insert_sql = ([[
+	INSERT INTO "%s"
 	("host","user","store","key","type","value")
 	VALUES (?,?,?,?,?,?);
-	]]
+	]]):format(engine.params.state_table);
 	if data and next(data) ~= nil then
 		local extradata = {};
 		for key, value in pairs(data) do
@@ -165,11 +165,11 @@
 end
 function keyval_store:users()
 	local ok, result = engine:transaction(function()
-		local select_sql = [[
+		local select_sql = ([[
 		SELECT DISTINCT "user"
-		FROM "prosody"
+		FROM "%s"
 		WHERE "host"=? AND "store"=?;
-		]];
+		]]):format(engine.params.state_table);
 		return engine:select(select_sql, host, self.store);
 	end);
 	if not ok then error(result); end
@@ -191,12 +191,12 @@
 map_store.remove = {};
 function map_store:get(username, key)
 	local ok, result = engine:transaction(function()
-		local query = [[
+		local query = ([[
 		SELECT "type", "value"
-		FROM "prosody"
+		FROM "%s"
 		WHERE "host"=? AND "user"=? AND "store"=? AND "key"=?
 		LIMIT 1
-		]];
+		]]):format(engine.params.state_table);
 		local data, err;
 		if type(key) == "string" and key ~= "" then
 			for row in engine:select(query, host, username or "", self.store, key) do
@@ -221,28 +221,29 @@
 end
 function map_store:set_keys(username, keydatas)
 	local ok, result = engine:write_transaction(function()
-		local delete_sql = [[
-		DELETE FROM "prosody"
+		local delete_sql = ([[
+		DELETE FROM "%s"
 		WHERE "host"=? AND "user"=? AND "store"=? AND "key"=?;
-		]];
-		local insert_sql = [[
-		INSERT INTO "prosody"
+		]]):format(engine.params.state_table);
+		local insert_sql = ([[
+		INSERT INTO "%s"
 		("host","user","store","key","type","value")
 		VALUES (?,?,?,?,?,?);
-		]];
-		local upsert_sql = [[
-		INSERT INTO "prosody"
+		]]):format(engine.params.state_table);
+		local upsert_sql = ([[
+		INSERT INTO "%s"
 		("host","user","store","key","type","value")
 		VALUES (?,?,?,?,?,?)
 		ON CONFLICT ("host", "user","store", "key")
 		DO UPDATE SET "type"=?, "value"=?;
-		]];
-		local select_extradata_sql = [[
+		]]):format(engine.params.state_table);
+		local select_extradata_sql = ([[
 		SELECT "type", "value"
-		FROM "prosody"
+		FROM "%s"
 		WHERE "host"=? AND "user"=? AND "store"=? AND "key"=?
 		LIMIT 1;
-		]];
+		]]):format(engine.params.state_table);
+
 		for key, data in pairs(keydatas) do
 			if type(key) == "string" and key ~= "" and has_upsert(engine) and data ~= self.remove then
 				local t, value = assert(serialize(data));
@@ -277,11 +278,11 @@
 		return nil, "get_all only supports non-empty string keys";
 	end
 	local ok, result = engine:transaction(function()
-		local query = [[
+		local query = ([[
 		SELECT "user", "type", "value"
-		FROM "prosody"
+		FROM "%s"
 		WHERE "host"=? AND "store"=? AND "key"=?
-		]];
+		]]):format(engine.params.state_table);
 
 		local data;
 		for row in engine:select(query, host, self.store, key) do
@@ -305,10 +306,10 @@
 		return nil, "delete_all only supports non-empty string keys";
 	end
 	local ok, result = engine:write_transaction(function()
-		local delete_sql = [[
-		DELETE FROM "prosody"
-		WHERE "host"=? AND "store"=? AND "key"=?;
-		]];
+		local delete_sql = ([[
+			DELETE FROM "%s"
+			WHERE "host"=? AND "store"=? AND "key"=?;
+		]]):format(engine.params.state_table);
 		engine:delete(delete_sql, host, self.store, key);
 		return true;
 	end);
@@ -335,10 +336,10 @@
 		if not item_count then
 			item_count_cache_miss();
 			local ok, ret = engine:write_transaction(function()
-				local count_sql = [[
-				SELECT COUNT(*) FROM "prosodyarchive"
+				local count_sql = ([[
+				SELECT COUNT(*) FROM "%s"
 				WHERE "host"=? AND "user"=? AND "store"=?;
-				]];
+				]]):format(engine.params.archive_table);
 				local result = engine:select(count_sql, host, user, store);
 				if result then
 					for row in result do
@@ -369,15 +370,15 @@
 	end
 	with = with or "";
 	local ok, ret = engine:write_transaction(function()
-		local delete_sql = [[
-		DELETE FROM "prosodyarchive"
+		local delete_sql = ([[
+		DELETE FROM "%s"
 		WHERE "host"=? AND "user"=? AND "store"=? AND "key"=?;
-		]];
-		local insert_sql = [[
-		INSERT INTO "prosodyarchive"
+		]]):format(engine.params.archive_table);
+		local insert_sql = ([[
+		INSERT INTO "%s"
 		("host", "user", "store", "when", "with", "key", "type", "value")
 		VALUES (?,?,?,?,?,?,?,?);
-		]];
+		]]):format(engine.params.archive_table);
 		if key then
 			-- TODO use UPSERT like map store
 			local result = engine:delete(delete_sql, host, user or "", store, key);
@@ -434,14 +435,15 @@
 		t_move(query.ids, 1, nids, nargs + 1, args);
 	end
 end
+
 local function archive_where_id_range(query, args, where)
 	-- Before or after specific item, exclusive
-	local id_lookup_sql = [[
+	local id_lookup_sql = ([[
 	SELECT "sort_id"
-	FROM "prosodyarchive"
+	FROM "%s"
 	WHERE "key" = ? AND "host" = ? AND "user" = ? AND "store" = ?
 	LIMIT 1;
-	]];
+	]]):format(engine.params.archive_table);
 	if query.after then  -- keys better be unique!
 		local after_id = nil;
 		for row in engine:select(id_lookup_sql, query.after, args[1], args[2], args[3]) do
@@ -482,12 +484,12 @@
 		total = nil;
 	end
 	local ok, result, err = engine:transaction(function()
-		local sql_query = [[
+		local sql_query = ([[
 		SELECT "key", "type", "value", "when", "with"
-		FROM "prosodyarchive"
-		WHERE %s
-		ORDER BY "sort_id" %s%s;
-		]];
+		FROM "%s"
+		WHERE %%s
+		ORDER BY "sort_id" %%s%%s;
+		]]):format(engine.params.archive_table);
 		local args = { host, user or "", store, };
 		local where = { "\"host\" = ?", "\"user\" = ?", "\"store\" = ?", };
 
@@ -496,7 +498,7 @@
 		-- Total matching
 		if query.total and not total then
 
-			local stats = engine:select("SELECT COUNT(*) FROM \"prosodyarchive\" WHERE "
+			local stats = engine:select(([[SELECT COUNT(*) FROM "%s" WHERE ]]):format(engine.params.archive_table)
 				.. t_concat(where, " AND "), unpack(args));
 			if stats then
 				for row in stats do
@@ -543,11 +545,11 @@
 	local user,store = username,self.store;
 	local ok, result = engine:write_transaction(function ()
 
-		local update_query = [[
-		UPDATE "prosodyarchive"
-		SET %s
-		WHERE %s
-		]];
+		local update_query = ([[
+		UPDATE "%s"
+		SET %%s
+		WHERE %%s
+		]]):format(engine.params.archive_table);
 		local args = { host, user or "", store, key };
 		local setf = {};
 		local where = { "\"host\" = ?", "\"user\" = ?", "\"store\" = ?", "\"key\" = ?"};
@@ -581,12 +583,12 @@
 	query = query or {};
 	local user,store = username,self.store;
 	local ok, result = engine:transaction(function()
-		local sql_query = [[
+		local sql_query = ([[
 		SELECT DISTINCT "with", COUNT(*), MIN("when"), MAX("when")
-		FROM "prosodyarchive"
-		WHERE %s
+		FROM "%s"
+		WHERE %%s
 		GROUP BY "with";
-		]];
+		]]):format(engine.params.archive_table);
 		local args = { host, user or "", store, };
 		local where = { "\"host\" = ?", "\"user\" = ?", "\"store\" = ?", };
 
@@ -621,7 +623,7 @@
 	query = query or {};
 	local user,store = username,self.store;
 	local ok, stmt = engine:write_transaction(function()
-		local sql_query = "DELETE FROM \"prosodyarchive\" WHERE %s;";
+		local sql_query = ([[DELETE FROM "%s" WHERE %%s; ]]):format(engine.params.archive_table);
 		local args = { host, user or "", store, };
 		local where = { "\"host\" = ?", "\"user\" = ?", "\"store\" = ?", };
 		if user == true then
@@ -634,35 +636,36 @@
 		if query.truncate == nil then
 			sql_query = sql_query:format(t_concat(where, " AND "));
 		elseif engine.params.driver == "MySQL" then
-			sql_query = [[
-			DELETE result FROM prosodyarchive AS result JOIN (
-				SELECT sort_id FROM prosodyarchive
-				WHERE %s
-				ORDER BY "sort_id" %s
-				LIMIT 18446744073709551615 OFFSET %s
-			) AS limiter on result.sort_id = limiter.sort_id;]];
+			sql_query = ([[
+			DELETE result FROM %s AS result JOIN (
+			SELECT sort_id FROM %s
+			WHERE %%s
+			ORDER BY "sort_id" %%s
+			LIMIT 18446744073709551615 OFFSET %%s
+			) AS limiter on
+			result.sort_id = limiter.sort_id;]]):format(engine.params.archive_table, engine.params.archive_table);
 
 			sql_query = string.format(sql_query, t_concat(where, " AND "),
 				query.reverse and "ASC" or "DESC", query.truncate);
 		else
 			args[#args+1] = query.truncate;
 			local unlimited = "ALL";
-			sql_query = [[
-			DELETE FROM "prosodyarchive"
+			sql_query = ([[
+			DELETE FROM "%s"
 			WHERE "sort_id" IN (
-				SELECT "sort_id" FROM "prosodyarchive"
-				WHERE %s
-				ORDER BY "sort_id" %s
-				LIMIT %s OFFSET ?
-			);]];
+				SELECT "sort_id" FROM "%s"
+				WHERE %%s
+				ORDER BY "sort_id" %%s
+				LIMIT %%s OFFSET ?
+			);]]):format(engine.params.archive_table, engine.params.archive_table);
 			if engine.params.driver == "SQLite3" then
 				if engine.sqlite_compile_options.enable_update_delete_limit then
-					sql_query = [[
-					DELETE FROM "prosodyarchive"
-					WHERE %s
-					ORDER BY "sort_id" %s
-					LIMIT %s OFFSET ?;
-					]];
+					sql_query = ([[
+					DELETE FROM "%s"
+					WHERE %%s
+					ORDER BY "sort_id" %%s
+					LIMIT %%s OFFSET ?;
+					]]):format(engine.params.archive_table);
 				end
 				unlimited = "-1";
 			end
@@ -688,11 +691,11 @@
 
 function archive_store:users()
 	local ok, result = engine:transaction(function()
-		local select_sql = [[
+		local select_sql = ([[
 		SELECT DISTINCT "user"
-		FROM "prosodyarchive"
+		FROM "%s"
 		WHERE "host"=? AND "store"=?;
-		]];
+		]]):format(engine.params.archive_table);
 		return engine:select(select_sql, host, self.store);
 	end);
 	if not ok then error(result); end
@@ -737,8 +740,8 @@
 end
 
 function driver:stores(username)
-	local query = "SELECT DISTINCT \"store\" FROM \"prosody\" WHERE \"host\"=? AND \"user\"" ..
-		(username == true and "!=?" or "=?");
+	local query = ([[SELECT DISTINCT "store" FROM "%s" WHERE "host"=? AND "user" ]]):format(engine.params.state_table) ..
+	              (username == true and "!=?" or "=? ");
 	if username == true or not username then
 		username = "";
 	end
@@ -751,8 +754,8 @@
 
 function driver:purge(username)
 	return engine:write_transaction(function()
-		engine:delete("DELETE FROM \"prosody\" WHERE \"host\"=? AND \"user\"=?", host, username);
-		engine:delete("DELETE FROM \"prosodyarchive\" WHERE \"host\"=? AND \"user\"=?", host, username);
+		engine:delete(([[DELETE FROM "%s" WHERE "host"=? AND "user"=? ]]):format(engine.params.state_table), host, username);
+		engine:delete(([[DELETE FROM "%s" WHERE "host"=? AND "user"=? ]]):format(engine.params.archive_table), host, username);
 	end);
 end
 
@@ -764,21 +767,21 @@
 	local Table, Column, Index = sql.Table, sql.Column, sql.Index;
 
 	local ProsodyTable = Table {
-		name = "prosody";
+		name = engine.params.state_table;
 		Column { name="host", type="TEXT", nullable=false };
 		Column { name="user", type="TEXT", nullable=false };
 		Column { name="store", type="TEXT", nullable=false };
 		Column { name="key", type="TEXT", nullable=false };
 		Column { name="type", type="TEXT", nullable=false };
 		Column { name="value", type="MEDIUMTEXT", nullable=false };
-		Index { name = "prosody_unique_index"; unique = engine.params.driver ~= "MySQL"; "host"; "user"; "store"; "key" };
+		Index { name = engine.params.state_table .. "_unique_index"; unique = engine.params.driver ~= "MySQL"; "host"; "user"; "store"; "key" };
 	};
 	engine:transaction(function()
 		ProsodyTable:create(engine);
 	end);
 
 	local ProsodyArchiveTable = Table {
-		name="prosodyarchive";
+		name=engine.params.archive_table;
 		Column { name="sort_id", type="INTEGER", primary_key=true, auto_increment=true };
 		Column { name="host", type="TEXT", nullable=false };
 		Column { name="user", type="TEXT", nullable=false };
@@ -788,10 +791,10 @@
 		Column { name="with", type="TEXT", nullable=false }; -- related id
 		Column { name="type", type="TEXT", nullable=false };
 		Column { name="value", type="MEDIUMTEXT", nullable=false };
-		Index { name="prosodyarchive_index", unique = engine.params.driver ~= "MySQL", "host", "user", "store", "key" };
-		Index { name="prosodyarchive_with_when", "host", "user", "store", "with", "when" };
-		Index { name="prosodyarchive_when", "host", "user", "store", "when" };
-		Index { name="prosodyarchive_sort", "host", "user", "store", "sort_id" };
+		Index { name=engine.params.archive_table .. "_index", unique = engine.params.driver ~= "MySQL", "host", "user", "store", "key" };
+		Index { name=engine.params.archive_table .. "_with_when", "host", "user", "store", "with", "when" };
+		Index { name=engine.params.archive_table .. "_when", "host", "user", "store", "when" };
+		Index { name=engine.params.archive_table .. "_sort", "host", "user", "store", "sort_id" };
 	};
 	engine:transaction(function()
 		ProsodyArchiveTable:create(engine);
@@ -804,12 +807,12 @@
 		local sql = get_sql_lib("MySQL");
 		local success,err = engine:transaction(function()
 			do
-				local result = assert(engine:execute("SHOW COLUMNS FROM \"prosody\" WHERE \"Field\"='value' and \"Type\"='text'"));
+				local result = assert(engine:execute(([[SHOW COLUMNS FROM "%s" WHERE "Field"='value' and "Type"='text' ]]):format(engine.params.state_table)));
 				if result:rowcount() > 0 then
 					changes = true;
 					if apply_changes then
 						module:log("info", "Upgrading database schema (value column size)...");
-						assert(engine:execute("ALTER TABLE \"prosody\" MODIFY COLUMN \"value\" MEDIUMTEXT"));
+						assert(engine:execute(([[ALTER TABLE "%s" MODIFY COLUMN "value" MEDIUMTEXT ]]):format(engine.params.state_table)));
 						module:log("info", "Database table automatically upgraded");
 					end
 				end
@@ -817,13 +820,13 @@
 
 			do
 				-- Ensure index is not unique (issue #1073)
-				local result = assert(engine:execute([[SHOW INDEX FROM prosodyarchive WHERE key_name='prosodyarchive_index' and non_unique=0]]));
+				local result = assert(engine:execute(([[SHOW INDEX FROM %s WHERE key_name='%s_index' and non_unique=0]]):format(engine.params.archive_table, engine.params.archive_table)));
 				if result:rowcount() > 0 then
 					changes = true;
 					if apply_changes then
-						module:log("info", "Upgrading database schema (prosodyarchive_index)...");
-						assert(engine:execute[[ALTER TABLE "prosodyarchive" DROP INDEX prosodyarchive_index;]]);
-						local new_index = sql.Index { table = "prosodyarchive", name="prosodyarchive_index", "host", "user", "store", "key" };
+						module:log("info", "Upgrading database schema (%s_index)...", engine.params.archive_table);
+						assert(engine:execute(([[ALTER TABLE "%s" DROP INDEX %s_index;]]):format(engine.params.archive_table, engine.params.archive_table)));
+						local new_index = sql.Index { table = engine.params.archive_table, name=engine.params.archive_table .. "_index", "host", "user", "store", "key" };
 						assert(engine:_create_index(new_index));
 						module:log("info", "Database table automatically upgraded");
 					end
@@ -842,9 +845,9 @@
 		local check_encoding_query = [[
 		SELECT "COLUMN_NAME","COLUMN_TYPE","TABLE_NAME"
 		FROM "information_schema"."columns"
-		WHERE "TABLE_NAME" LIKE 'prosody%%'
+		WHERE ("TABLE_NAME" = ']] .. engine.params.state_table .. [[' OR "TABLE_NAME" = ']] .. engine.params.archive_table .. [[')
 		AND "TABLE_SCHEMA" = ?
-		AND ( "CHARACTER_SET_NAME"!=? OR "COLLATION_NAME"!=?);
+		AND ("CHARACTER_SET_NAME"!=? OR "COLLATION_NAME"!=?);
 		]];
 		-- FIXME Is it ok to ignore the return values from this?
 		engine:transaction(function()
@@ -878,26 +881,26 @@
 		local indices = {};
 		engine:transaction(function ()
 			if params.driver == "SQLite3" then
-				for row in engine:select [[SELECT "name" FROM "sqlite_schema" WHERE "type"='index' AND "tbl_name"='prosody';]] do
+				for row in engine:select([[SELECT "name" FROM "sqlite_schema" WHERE "type"='index' AND "tbl_name"=']] .. engine.params.state_table .. [[';]]) do
 					indices[row[1]] = true;
 				end
 			elseif params.driver == "PostgreSQL" then
-				for row in engine:select [[SELECT "indexname" FROM "pg_indexes" WHERE "tablename"='prosody';]] do
+				for row in engine:select([[SELECT "indexname" FROM "pg_indexes" WHERE "tablename"=']] .. engine.params.state_table .. [[';]]) do
 					indices[row[1]] = true;
 				end
 			end
 		end)
-		if indices["prosody_index"] then
+		if indices[engine.params.state_table .. "_index"] then
 			local success = engine:transaction(function ()
-				return assert(engine:execute([[DROP INDEX "prosody_index";]]));
+				return assert(engine:execute(([[DROP INDEX "%s_index";]]):format(engine.params.state_table)));
 			end);
 			if not success then
-				module:log("error", "Failed to delete obsolete index \"prosody_index\"");
+				module:log("error", "Failed to delete obsolete index \"%s_index\"", engine.params.state_table);
 				return false;
 			end
 		end
-		if not indices["prosody_unique_index"] then
-			module:log("warn", "Index \"prosody_unique_index\" does not exist, performance may be worse than normal!");
+		if not indices[engine.params.state_table .. "_unique_index"] then
+			module:log("warn", "Index \"%s_unique_index\" does not exist, performance may be worse than normal!", engine.params.state_table);
 			engine.has_upsert_index = false;
 		else
 			engine.has_upsert_index = true;
@@ -923,6 +926,9 @@
 		password = params.password;
 		host = params.host;
 		port = params.port;
+		-- Optional table names for custom databases
+		state_table = params.state_table or "prosody";
+		archive_table = params.archive_table or "prosodyarchive";
 	};
 end

Reply via email to