Diff

util/sql.lua @ 5888:f3e408ae59a6

util.sql: Find out if MySQL supports utf8mb4 and use that
author Kim Alvefur <zash@zash.se>
date Tue, 29 Oct 2013 11:42:55 +0100
parent 5887:1f860279b2f8
child 5889:ea6a3adb6a69
line wrap: on
line diff
--- a/util/sql.lua	Mon Oct 28 23:20:25 2013 +0100
+++ b/util/sql.lua	Tue Oct 29 11:42:55 2013 +0100
@@ -291,14 +291,19 @@
 end
 function engine:set_encoding() -- to UTF-8
 	if self.params.driver == "SQLite3" then return end
-	local set_names_query = "SET NAMES 'utf8';";
-	if self.params.driver == "MySQL" then
+	local driver = self.params.driver;
+	local set_names_query = "SET NAMES '%s';"
+	local charset = "utf8";
+	if driver == "MySQL" then
 		set_names_query = set_names_query:gsub(";$", " COLLATE 'utf8_bin';");
+		local ok, charsets = self:transaction(function()
+			return self:select"SELECT `CHARACTER_SET_NAME` FROM `CHARACTER_SETS` WHERE `CHARACTER_SET_NAME` LIKE 'utf8%' ORDER BY MAXLEN DESC LIMIT 1;";
+		end);
+		local row = ok and charsets();
+		charset = row and row[1] or charset;
 	end
-	local success,err = engine:transaction(function() return engine:execute(set_names_query); end);
-	if not success then
-		log("error", "Failed to set database connection encoding to UTF8: %s", err);
-	end
+	self.charset = charset;
+	return self:transaction(function() return engine:execute(set_names_query:format(charset)); end);
 end
 local engine_mt = { __index = engine };