mod_storage_sql: Log error when failing to update MySQL schema
[prosody.git] / plugins / mod_storage_sql.lua
index 7917958d385245346ad28e702cf387d89b8f4f90..57331ac0a7c40895bd63990c5b07f1754b963bf7 100644 (file)
@@ -68,6 +68,8 @@ local function create_table()
        local create_sql = "CREATE TABLE `prosody` (`host` TEXT, `user` TEXT, `store` TEXT, `key` TEXT, `type` TEXT, `value` TEXT);";
        if params.driver == "PostgreSQL" then
                create_sql = create_sql:gsub("`", "\"");
+       elseif params.driver == "MySQL" then
+               create_sql = create_sql:gsub("`value` TEXT", "`value` MEDIUMTEXT");
        end
        
        local stmt = connection:prepare(create_sql);
@@ -91,12 +93,41 @@ local function create_table()
                        if not(ok and commit_ok) then
                                module:log("warn", "Failed to create index (%s), lookups may not be optimised", err or commit_err);
                        end
+               else -- COMPAT: Upgrade tables from 0.8.0
+                       -- Failed to create, but check existing MySQL table here
+                       local stmt = connection:prepare("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'");
+                       local ok = stmt:execute();
+                       local commit_ok = connection:commit();
+                       if ok and commit_ok then
+                               if stmt:rowcount() > 0 then
+                                       local stmt = connection:prepare("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT");
+                                       local ok = stmt:execute();
+                                       local commit_ok = connection:commit();
+                                       if ok and commit_ok then
+                                               module:log("info", "Database table automatically upgraded");
+                                       end
+                               end
+                               repeat until not stmt:fetch();
+                       else
+                               module:log("error", "Failed to upgrade database schema, please see http://prosody.im/doc/mysql for help");
+                       end
                end
        end
 end
 
 do -- process options to get a db connection
-       DBI = require "DBI";
+       local ok;
+       prosody.unlock_globals();
+       ok, DBI = pcall(require, "DBI");
+       if not ok then
+               package.loaded["DBI"] = {};
+               module:log("error", "Failed to load the LuaDBI library for accessing SQL databases: %s", DBI);
+               module:log("error", "More information on installing LuaDBI can be found at http://prosody.im/doc/depends#luadbi");
+       end
+       prosody.lock_globals();
+       if not ok or not DBI.Connect then
+               return; -- Halt loading of this module
+       end
 
        params = params or { driver = "SQLite3" };