Diff

plugins/mod_storage_sql.lua @ 5054:97385c45e670

mod_storage_sql: Keep connections in a shared cache table
author Kim Alvefur <zash@zash.se>
date Mon, 30 Jul 2012 01:54:07 +0200
parent 5040:685403a6fee1
child 5055:d466d2088a61
line wrap: on
line diff
--- a/plugins/mod_storage_sql.lua	Mon Jul 30 00:40:02 2012 +0100
+++ b/plugins/mod_storage_sql.lua	Mon Jul 30 01:54:07 2012 +0200
@@ -27,12 +27,28 @@
 local setmetatable = setmetatable;
 local xpcall = xpcall;
 local json = require "util.json";
+local build_url = require"socket.url".build;
 
 local DBI;
 local connection;
 local host,user,store = module.host;
 local params = module:get_option("sql");
 
+local dburi;
+local connections = module:shared "/*/sql/connection-cache";
+
+local function db2uri(params)
+	return build_url{
+		scheme = params.driver,
+		user = params.username,
+		password = params.password,
+		host = params.host,
+		port = params.port,
+		path = params.database,
+	};
+end
+
+
 local resolve_relative_path = require "core.configmanager".resolve_relative_path;
 
 local function test_connection()
@@ -42,6 +58,7 @@
 	else
 		module:log("debug", "Database connection closed");
 		connection = nil;
+		connections[dburi] = nil;
 	end
 end
 local function connect()
@@ -60,6 +77,8 @@
 		module:log("debug", "Successfully connected to database");
 		dbh:autocommit(false); -- don't commit automatically
 		connection = dbh;
+
+		connections[dburi] = dbh;
 		return connection;
 	end
 end
@@ -146,6 +165,9 @@
 	end
 	
 	assert(params.driver and params.database, "Both the SQL driver and the database need to be specified");
+
+	dburi = db2uri(params);
+	connection = connections[dburi];
 	
 	assert(connect());