Mantis#1736. Thank you kindly, StrawberryFride for a patch that:

Many issues with handling connections in MSSQL, have rearchitected to 
ensure that connections are always opened and closed in a timely fashion 
& disposed of cleanly, and removed unnecessary lock statements. SQL 
Server performance seems to have improved considerably as a result, 
and various timeout errors seem to have been fixed.
0.6.0-stable
Charles Krinke 2008-07-17 13:43:31 +00:00
parent ed4241583f
commit e8412dcd42
8 changed files with 780 additions and 709 deletions

View File

@ -0,0 +1,216 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace OpenSim.Data.MSSQL
{
/// <summary>
/// Encapsulates a SqlCommand object but ensures that when it is disposed, its connection is closed and disposed also.
/// </summary>
internal class AutoClosingSqlCommand : IDbCommand
{
private SqlCommand realCommand;
public AutoClosingSqlCommand(SqlCommand cmd)
{
realCommand = cmd;
}
#region IDbCommand Members
public void Cancel()
{
realCommand.Cancel();
}
public string CommandText
{
get
{
return realCommand.CommandText;
}
set
{
realCommand.CommandText = value;
}
}
public int CommandTimeout
{
get
{
return realCommand.CommandTimeout;
}
set
{
realCommand.CommandTimeout = value;
}
}
public CommandType CommandType
{
get
{
return realCommand.CommandType;
}
set
{
realCommand.CommandType = value;
}
}
IDbConnection IDbCommand.Connection
{
get
{
return realCommand.Connection;
}
set
{
realCommand.Connection = (SqlConnection) value;
}
}
public SqlConnection Connection
{
get
{
return realCommand.Connection;
}
}
IDbDataParameter IDbCommand.CreateParameter()
{
return realCommand.CreateParameter();
}
public SqlParameter CreateParameter()
{
return realCommand.CreateParameter();
}
public int ExecuteNonQuery()
{
return realCommand.ExecuteNonQuery();
}
IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior)
{
return realCommand.ExecuteReader(behavior);
}
public SqlDataReader ExecuteReader(CommandBehavior behavior)
{
return realCommand.ExecuteReader(behavior);
}
IDataReader IDbCommand.ExecuteReader()
{
return realCommand.ExecuteReader();
}
public SqlDataReader ExecuteReader()
{
return realCommand.ExecuteReader();
}
public object ExecuteScalar()
{
return realCommand.ExecuteScalar();
}
IDataParameterCollection IDbCommand.Parameters
{
get { return realCommand.Parameters; }
}
public SqlParameterCollection Parameters
{
get { return realCommand.Parameters; }
}
public void Prepare()
{
realCommand.Prepare();
}
IDbTransaction IDbCommand.Transaction
{
get
{
return realCommand.Transaction;
}
set
{
realCommand.Transaction = (SqlTransaction) value;
}
}
UpdateRowSource IDbCommand.UpdatedRowSource
{
get
{
return realCommand.UpdatedRowSource;
}
set
{
realCommand.UpdatedRowSource = value;
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
SqlConnection conn = realCommand.Connection;
try
{
realCommand.Dispose();
}
finally
{
try
{
conn.Close();
}
finally
{
conn.Dispose();
}
}
}
#endregion
}
}

View File

@ -86,19 +86,14 @@ namespace OpenSim.Data.MSSQL
/// <returns></returns> /// <returns></returns>
override public AssetBase FetchAsset(LLUUID assetID) override public AssetBase FetchAsset(LLUUID assetID)
{ {
AssetBase asset = null;
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["id"] = assetID.ToString(); param["id"] = assetID.ToString();
IDbCommand result = database.Query("SELECT * FROM assets WHERE id = @id", param); using (IDbCommand result = database.Query("SELECT * FROM assets WHERE id = @id", param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
asset = database.getAssetRow(reader); return database.getAssetRow(reader);
reader.Close(); }
result.Dispose();
return asset;
} }
/// <summary> /// <summary>
@ -113,15 +108,13 @@ namespace OpenSim.Data.MSSQL
} }
SqlCommand cmd = using (AutoClosingSqlCommand cmd =
new SqlCommand( database.Query(
"INSERT INTO assets ([id], [name], [description], [assetType], [local], [temporary], [data])" + "INSERT INTO assets ([id], [name], [description], [assetType], [local], [temporary], [data])" +
" VALUES " + " VALUES " +
"(@id, @name, @description, @assetType, @local, @temporary, @data)", "(@id, @name, @description, @assetType, @local, @temporary, @data)"))
database.getConnection());
using (cmd)
{ {
//SqlParameter p = cmd.Parameters.Add("id", SqlDbType.NVarChar); //SqlParameter p = cmd.Parameters.Add("id", SqlDbType.NVarChar);
//p.Value = asset.FullID.ToString(); //p.Value = asset.FullID.ToString();
cmd.Parameters.AddWithValue("id", asset.FullID.ToString()); cmd.Parameters.AddWithValue("id", asset.FullID.ToString());
@ -135,16 +128,8 @@ namespace OpenSim.Data.MSSQL
h.Value = asset.Temporary; h.Value = asset.Temporary;
SqlParameter i = cmd.Parameters.Add("data", SqlDbType.Image); SqlParameter i = cmd.Parameters.Add("data", SqlDbType.Image);
i.Value = asset.Data; i.Value = asset.Data;
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
cmd.Dispose(); cmd.ExecuteNonQuery();
} }
} }
@ -154,14 +139,15 @@ namespace OpenSim.Data.MSSQL
/// <param name="asset">the asset</param> /// <param name="asset">the asset</param>
override public void UpdateAsset(AssetBase asset) override public void UpdateAsset(AssetBase asset)
{ {
SqlCommand command = new SqlCommand("UPDATE assets set id = @id, " + using (IDbCommand command = database.Query("UPDATE assets set id = @id, " +
"name = @name, " + "name = @name, " +
"description = @description," + "description = @description," +
"assetType = @assetType," + "assetType = @assetType," +
"local = @local," + "local = @local," +
"temporary = @temporary," + "temporary = @temporary," +
"data = @data where " + "data = @data where " +
"id = @keyId;", database.getConnection()); "id = @keyId;"))
{
SqlParameter param1 = new SqlParameter("@id", asset.FullID.ToString()); SqlParameter param1 = new SqlParameter("@id", asset.FullID.ToString());
SqlParameter param2 = new SqlParameter("@name", asset.Name); SqlParameter param2 = new SqlParameter("@name", asset.Name);
SqlParameter param3 = new SqlParameter("@description", asset.Description); SqlParameter param3 = new SqlParameter("@description", asset.Description);
@ -188,6 +174,7 @@ namespace OpenSim.Data.MSSQL
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
}
/// <summary> /// <summary>
/// Check if asset exist in database /// Check if asset exist in database
@ -228,12 +215,12 @@ namespace OpenSim.Data.MSSQL
/// <remarks>it use mssql_connection.ini</remarks> /// <remarks>it use mssql_connection.ini</remarks>
override public void Initialise() override public void Initialise()
{ {
IniFile GridDataMySqlFile = new IniFile("mssql_connection.ini"); IniFile gridDataMSSqlFile = new IniFile("mssql_connection.ini");
string settingDataSource = GridDataMySqlFile.ParseFileReadValue("data_source"); string settingDataSource = gridDataMSSqlFile.ParseFileReadValue("data_source");
string settingInitialCatalog = GridDataMySqlFile.ParseFileReadValue("initial_catalog"); string settingInitialCatalog = gridDataMSSqlFile.ParseFileReadValue("initial_catalog");
string settingPersistSecurityInfo = GridDataMySqlFile.ParseFileReadValue("persist_security_info"); string settingPersistSecurityInfo = gridDataMSSqlFile.ParseFileReadValue("persist_security_info");
string settingUserId = GridDataMySqlFile.ParseFileReadValue("user_id"); string settingUserId = gridDataMSSqlFile.ParseFileReadValue("user_id");
string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); string settingPassword = gridDataMSSqlFile.ParseFileReadValue("password");
database = database =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,

View File

@ -1758,7 +1758,7 @@ namespace OpenSim.Data.MSSQL
} }
catch (SqlException) catch (SqlException)
{ {
m_log.Info("[REGION DB]: MySql Database doesn't exist... creating"); m_log.Info("[REGION DB]: MS Sql Database doesn't exist... creating");
InitDB(conn); InitDB(conn);
} }

View File

@ -84,12 +84,11 @@ namespace OpenSim.Data.MSSQL
/// </summary> /// </summary>
private void TestTables() private void TestTables()
{ {
IDbCommand cmd = database.Query("SELECT TOP 1 * FROM "+m_regionsTableName, new Dictionary<string, string>()); using (IDbCommand cmd = database.Query("SELECT TOP 1 * FROM " + m_regionsTableName, new Dictionary<string, string>()))
{
try try
{ {
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Dispose();
} }
catch (Exception) catch (Exception)
{ {
@ -97,13 +96,14 @@ namespace OpenSim.Data.MSSQL
database.ExecuteResourceSql("Mssql-regions.sql"); database.ExecuteResourceSql("Mssql-regions.sql");
} }
} }
}
/// <summary> /// <summary>
/// Shuts down the grid interface /// Shuts down the grid interface
/// </summary> /// </summary>
override public void Close() override public void Close()
{ {
database.Close(); // nothing to close
} }
/// <summary> /// <summary>
@ -146,33 +146,23 @@ namespace OpenSim.Data.MSSQL
/// <returns>Sim profile</returns> /// <returns>Sim profile</returns>
override public RegionProfileData GetProfileByHandle(ulong handle) override public RegionProfileData GetProfileByHandle(ulong handle)
{ {
IDataReader reader = null;
try
{
if (database.getConnection().State == ConnectionState.Closed)
{
database.Reconnect();
}
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["handle"] = handle.ToString(); param["handle"] = handle.ToString();
IDbCommand result = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE regionHandle = @handle", param);
reader = result.ExecuteReader();
RegionProfileData row = database.getRegionRow(reader); try
reader.Close();
result.Dispose();
return row;
}
catch (Exception)
{ {
if (reader != null) using (IDbCommand result = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE regionHandle = @handle", param))
using (IDataReader reader = result.ExecuteReader())
{ {
reader.Close(); return database.getRegionRow(reader);
} }
} }
catch
{
return null; return null;
} }
}
/// <summary> /// <summary>
/// Returns a sim profile from its UUID /// Returns a sim profile from its UUID
@ -183,14 +173,13 @@ namespace OpenSim.Data.MSSQL
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["uuid"] = uuid.ToString(); param["uuid"] = uuid.ToString();
IDbCommand result = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE uuid = @uuid", param);
IDataReader reader = result.ExecuteReader();
RegionProfileData row = database.getRegionRow(reader); using (IDbCommand result = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE uuid = @uuid", param))
reader.Close(); using (IDataReader reader = result.ExecuteReader())
result.Dispose(); {
return database.getRegionRow(reader);
}
return row;
} }
/// <summary> /// <summary>
@ -203,26 +192,20 @@ namespace OpenSim.Data.MSSQL
if (regionName.Length > 2) if (regionName.Length > 2)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
// Add % because this is a like query. // Add % because this is a like query.
param["?regionName"] = regionName + "%"; param["?regionName"] = regionName + "%";
// Order by statement will return shorter matches first. Only returns one record or no record. // Order by statement will return shorter matches first. Only returns one record or no record.
IDbCommand result = database.Query("SELECT top 1 * FROM " + m_regionsTableName + " WHERE regionName like ?regionName order by regionName", param); using (IDbCommand result = database.Query("SELECT top 1 * FROM " + m_regionsTableName + " WHERE regionName like ?regionName order by regionName", param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row = database.getRegionRow(reader); return database.getRegionRow(reader);
reader.Close();
result.Dispose();
return row;
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
@ -324,12 +307,13 @@ namespace OpenSim.Data.MSSQL
try try
{ {
IDbCommand result = database.Query(sql, parameters); using (IDbCommand result = database.Query(sql, parameters))
{
if (result.ExecuteNonQuery() == 1) if (result.ExecuteNonQuery() == 1)
returnval = true; returnval = true;
result.Dispose(); }
} }
catch (Exception e) catch (Exception e)
{ {
@ -347,17 +331,15 @@ namespace OpenSim.Data.MSSQL
{ {
//Insert new region //Insert new region
string sql = string sql =
"INSERT INTO " + m_regionsTableName + " ([regionHandle], [regionName], [uuid], [regionRecvKey], [regionSecret], [regionSendKey], [regionDataURI], "; "INSERT INTO " + m_regionsTableName + @" ([regionHandle], [regionName], [uuid], [regionRecvKey], [regionSecret], [regionSendKey], [regionDataURI],
sql += [serverIP], [serverPort], [serverURI], [locX], [locY], [locZ], [eastOverrideHandle], [westOverrideHandle],
"[serverIP], [serverPort], [serverURI], [locX], [locY], [locZ], [eastOverrideHandle], [westOverrideHandle], [southOverrideHandle], [northOverrideHandle], [regionAssetURI], [regionAssetRecvKey], "; [southOverrideHandle], [northOverrideHandle], [regionAssetURI], [regionAssetRecvKey], [regionAssetSendKey],
sql += [regionUserURI], [regionUserRecvKey], [regionUserSendKey], [regionMapTexture], [serverHttpPort],
"[regionAssetSendKey], [regionUserURI], [regionUserRecvKey], [regionUserSendKey], [regionMapTexture], [serverHttpPort], [serverRemotingPort], [owner_uuid]) VALUES "; [serverRemotingPort], [owner_uuid])
VALUES (@regionHandle, @regionName, @uuid, @regionRecvKey, @regionSecret, @regionSendKey, @regionDataURI,
sql += "(@regionHandle, @regionName, @uuid, @regionRecvKey, @regionSecret, @regionSendKey, @regionDataURI, "; @serverIP, @serverPort, @serverURI, @locX, @locY, @locZ, @eastOverrideHandle, @westOverrideHandle,
sql += @southOverrideHandle, @northOverrideHandle, @regionAssetURI, @regionAssetRecvKey, @regionAssetSendKey,
"@serverIP, @serverPort, @serverURI, @locX, @locY, @locZ, @eastOverrideHandle, @westOverrideHandle, @southOverrideHandle, @northOverrideHandle, @regionAssetURI, @regionAssetRecvKey, "; @regionUserURI, @regionUserRecvKey, @regionUserSendKey, @regionMapTexture, @serverHttpPort, @serverRemotingPort, @owner_uuid);";
sql +=
"@regionAssetSendKey, @regionUserURI, @regionUserRecvKey, @regionUserSendKey, @regionMapTexture, @serverHttpPort, @serverRemotingPort, @owner_uuid);";
Dictionary<string, string> parameters = new Dictionary<string, string>(); Dictionary<string, string> parameters = new Dictionary<string, string>();
@ -393,12 +375,11 @@ namespace OpenSim.Data.MSSQL
try try
{ {
IDbCommand result = database.Query(sql, parameters); using (IDbCommand result = database.Query(sql, parameters))
{
if (result.ExecuteNonQuery() == 1) if (result.ExecuteNonQuery() == 1)
returnval = true; returnval = true;
}
result.Dispose();
} }
catch (Exception e) catch (Exception e)
{ {

View File

@ -67,12 +67,12 @@ namespace OpenSim.Data.MSSQL
public void Initialise(string connect) public void Initialise(string connect)
{ {
// TODO: actually use the provided connect string // TODO: actually use the provided connect string
IniFile GridDataMySqlFile = new IniFile("mssql_connection.ini"); IniFile gridDataMSSqlFile = new IniFile("mssql_connection.ini");
string settingDataSource = GridDataMySqlFile.ParseFileReadValue("data_source"); string settingDataSource = gridDataMSSqlFile.ParseFileReadValue("data_source");
string settingInitialCatalog = GridDataMySqlFile.ParseFileReadValue("initial_catalog"); string settingInitialCatalog = gridDataMSSqlFile.ParseFileReadValue("initial_catalog");
string settingPersistSecurityInfo = GridDataMySqlFile.ParseFileReadValue("persist_security_info"); string settingPersistSecurityInfo = gridDataMSSqlFile.ParseFileReadValue("persist_security_info");
string settingUserId = GridDataMySqlFile.ParseFileReadValue("user_id"); string settingUserId = gridDataMSSqlFile.ParseFileReadValue("user_id");
string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); string settingPassword = gridDataMSSqlFile.ParseFileReadValue("password");
database = database =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
@ -164,30 +164,27 @@ namespace OpenSim.Data.MSSQL
public List<InventoryItemBase> getInventoryInFolder(LLUUID folderID) public List<InventoryItemBase> getInventoryInFolder(LLUUID folderID)
{ {
try try
{
lock (database)
{ {
List<InventoryItemBase> items = new List<InventoryItemBase>(); List<InventoryItemBase> items = new List<InventoryItemBase>();
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["parentFolderID"] = folderID.ToString(); param["parentFolderID"] = folderID.ToString();
IDbCommand result = using (IDbCommand result =
database.Query("SELECT * FROM inventoryitems WHERE parentFolderID = @parentFolderID", param); database.Query("SELECT * FROM inventoryitems WHERE parentFolderID = @parentFolderID", param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
while (reader.Read()) while (reader.Read())
items.Add(readInventoryItem(reader)); items.Add(readInventoryItem(reader));
reader.Close(); reader.Close();
result.Dispose(); }
return items; return items;
} }
}
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
@ -201,31 +198,27 @@ namespace OpenSim.Data.MSSQL
public List<InventoryFolderBase> getUserRootFolders(LLUUID user) public List<InventoryFolderBase> getUserRootFolders(LLUUID user)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["uuid"] = user.ToString(); param["uuid"] = user.ToString();
param["zero"] = LLUUID.Zero.ToString(); param["zero"] = LLUUID.Zero.ToString();
IDbCommand result = using (IDbCommand result =
database.Query( database.Query(
"SELECT * FROM inventoryfolders WHERE parentFolderID = @zero AND agentID = @uuid", param); "SELECT * FROM inventoryfolders WHERE parentFolderID = @zero AND agentID = @uuid", param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>(); List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read()) while (reader.Read())
items.Add(readInventoryFolder(reader)); items.Add(readInventoryFolder(reader));
reader.Close();
result.Dispose();
return items; return items;
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
@ -239,17 +232,16 @@ namespace OpenSim.Data.MSSQL
public InventoryFolderBase getUserRootFolder(LLUUID user) public InventoryFolderBase getUserRootFolder(LLUUID user)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["uuid"] = user.ToString(); param["uuid"] = user.ToString();
param["zero"] = LLUUID.Zero.ToString(); param["zero"] = LLUUID.Zero.ToString();
IDbCommand result = using (IDbCommand result =
database.Query( database.Query(
"SELECT * FROM inventoryfolders WHERE parentFolderID = @zero AND agentID = @uuid", param); "SELECT * FROM inventoryfolders WHERE parentFolderID = @zero AND agentID = @uuid", param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>(); List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read()) while (reader.Read())
@ -267,15 +259,12 @@ namespace OpenSim.Data.MSSQL
rootFolder = items[0]; rootFolder = items[0];
} }
reader.Close();
result.Dispose();
return rootFolder; return rootFolder;
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
@ -289,31 +278,24 @@ namespace OpenSim.Data.MSSQL
public List<InventoryFolderBase> getInventoryFolders(LLUUID parentID) public List<InventoryFolderBase> getInventoryFolders(LLUUID parentID)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["parentFolderID"] = parentID.ToString(); param["parentFolderID"] = parentID.ToString();
using (IDbCommand result =
IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = @parentFolderID", param))
database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = @parentFolderID", param); using (IDataReader reader = result.ExecuteReader())
IDataReader reader = result.ExecuteReader(); {
List<InventoryFolderBase> items = new List<InventoryFolderBase>(); List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read()) while (reader.Read())
items.Add(readInventoryFolder(reader)); items.Add(readInventoryFolder(reader));
reader.Close();
result.Dispose();
return items; return items;
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
@ -368,29 +350,24 @@ namespace OpenSim.Data.MSSQL
public InventoryItemBase getInventoryItem(LLUUID itemID) public InventoryItemBase getInventoryItem(LLUUID itemID)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["inventoryID"] = itemID.ToString(); param["inventoryID"] = itemID.ToString();
IDbCommand result = using (IDbCommand result =
database.Query("SELECT * FROM inventoryitems WHERE inventoryID = @inventoryID", param); database.Query("SELECT * FROM inventoryitems WHERE inventoryID = @inventoryID", param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
InventoryItemBase item = null; InventoryItemBase item = null;
if (reader.Read()) if (reader.Read())
item = readInventoryItem(reader); item = readInventoryItem(reader);
reader.Close();
result.Dispose();
return item; return item;
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
return null; return null;
@ -430,26 +407,23 @@ namespace OpenSim.Data.MSSQL
public InventoryFolderBase getInventoryFolder(LLUUID folderID) public InventoryFolderBase getInventoryFolder(LLUUID folderID)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["uuid"] = folderID.ToString(); param["uuid"] = folderID.ToString();
IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE folderID = @uuid", param); using (IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE folderID = @uuid", param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
reader.Read(); reader.Read();
InventoryFolderBase folder = readInventoryFolder(reader); InventoryFolderBase folder = readInventoryFolder(reader);
reader.Close();
result.Dispose();
return folder; return folder;
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
@ -479,9 +453,8 @@ namespace OpenSim.Data.MSSQL
+ ", @inventoryBasePermissions, @inventoryEveryOnePermissions, @salePrice, @saleType" + ", @inventoryBasePermissions, @inventoryEveryOnePermissions, @salePrice, @saleType"
+ ", @creationDate, @groupID, @groupOwned, @flags);"; + ", @creationDate, @groupID, @groupOwned, @flags);";
try using (AutoClosingSqlCommand command = database.Query(sql))
{ {
SqlCommand command = new SqlCommand(sql, database.getConnection());
command.Parameters.AddWithValue("inventoryID", item.ID.ToString()); command.Parameters.AddWithValue("inventoryID", item.ID.ToString());
command.Parameters.AddWithValue("assetID", item.AssetID.ToString()); command.Parameters.AddWithValue("assetID", item.AssetID.ToString());
command.Parameters.AddWithValue("assetType", item.AssetType.ToString()); command.Parameters.AddWithValue("assetType", item.AssetType.ToString());
@ -502,8 +475,9 @@ namespace OpenSim.Data.MSSQL
command.Parameters.AddWithValue("groupOwned", item.GroupOwned); command.Parameters.AddWithValue("groupOwned", item.GroupOwned);
command.Parameters.AddWithValue("flags", ConvertUint32BitFieldToInt32(item.Flags)); command.Parameters.AddWithValue("flags", ConvertUint32BitFieldToInt32(item.Flags));
try
{
command.ExecuteNonQuery(); command.ExecuteNonQuery();
command.Dispose();
} }
catch (SqlException e) catch (SqlException e)
{ {
@ -511,13 +485,15 @@ namespace OpenSim.Data.MSSQL
} }
} }
}
/// <summary> /// <summary>
/// Updates the specified inventory item /// Updates the specified inventory item
/// </summary> /// </summary>
/// <param name="item">Inventory item to update</param> /// <param name="item">Inventory item to update</param>
public void updateInventoryItem(InventoryItemBase item) public void updateInventoryItem(InventoryItemBase item)
{ {
SqlCommand command = new SqlCommand("UPDATE inventoryitems set inventoryID = @inventoryID, " + using (AutoClosingSqlCommand command = database.Query("UPDATE inventoryitems set inventoryID = @inventoryID, " +
"assetID = @assetID, " + "assetID = @assetID, " +
"assetType = @assetType," + "assetType = @assetType," +
"parentFolderID = @parentFolderID," + "parentFolderID = @parentFolderID," +
@ -536,7 +512,8 @@ namespace OpenSim.Data.MSSQL
"groupID = @groupID," + "groupID = @groupID," +
"groupOwned = @groupOwned," + "groupOwned = @groupOwned," +
"flags = @flags where " + "flags = @flags where " +
"inventoryID = @keyInventoryID;", database.getConnection()); "inventoryID = @keyInventoryID;"))
{
command.Parameters.AddWithValue("inventoryID", item.ID.ToString()); command.Parameters.AddWithValue("inventoryID", item.ID.ToString());
command.Parameters.AddWithValue("assetID", item.AssetID.ToString()); command.Parameters.AddWithValue("assetID", item.AssetID.ToString());
command.Parameters.AddWithValue("assetType", item.AssetType.ToString()); command.Parameters.AddWithValue("assetType", item.AssetType.ToString());
@ -567,6 +544,7 @@ namespace OpenSim.Data.MSSQL
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
}
/// <summary> /// <summary>
/// Delete an item in inventory database /// Delete an item in inventory database
@ -579,13 +557,13 @@ namespace OpenSim.Data.MSSQL
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["uuid"] = itemID.ToString(); param["uuid"] = itemID.ToString();
IDbCommand cmd = database.Query("DELETE FROM inventoryitems WHERE inventoryID=@uuid", param); using (IDbCommand cmd = database.Query("DELETE FROM inventoryitems WHERE inventoryID=@uuid", param))
{
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Dispose(); }
} }
catch (SqlException e) catch (SqlException e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -601,7 +579,8 @@ namespace OpenSim.Data.MSSQL
sql += "(@folderID, @agentID, @parentFolderID, @folderName, @type, @version);"; sql += "(@folderID, @agentID, @parentFolderID, @folderName, @type, @version);";
SqlCommand command = new SqlCommand(sql, database.getConnection()); using (AutoClosingSqlCommand command = database.Query(sql))
{
command.Parameters.AddWithValue("folderID", folder.ID.ToString()); command.Parameters.AddWithValue("folderID", folder.ID.ToString());
command.Parameters.AddWithValue("agentID", folder.Owner.ToString()); command.Parameters.AddWithValue("agentID", folder.Owner.ToString());
command.Parameters.AddWithValue("parentFolderID", folder.ParentID.ToString()); command.Parameters.AddWithValue("parentFolderID", folder.ParentID.ToString());
@ -613,13 +592,13 @@ namespace OpenSim.Data.MSSQL
{ {
//IDbCommand result = database.Query(sql, param); //IDbCommand result = database.Query(sql, param);
command.ExecuteNonQuery(); command.ExecuteNonQuery();
command.Dispose();
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
}
/// <summary> /// <summary>
/// Updates an inventory folder /// Updates an inventory folder
@ -627,13 +606,14 @@ namespace OpenSim.Data.MSSQL
/// <param name="folder">Folder to update</param> /// <param name="folder">Folder to update</param>
public void updateInventoryFolder(InventoryFolderBase folder) public void updateInventoryFolder(InventoryFolderBase folder)
{ {
SqlCommand command = new SqlCommand("UPDATE inventoryfolders set folderID = @folderID, " + using (IDbCommand command = database.Query("UPDATE inventoryfolders set folderID = @folderID, " +
"agentID = @agentID, " + "agentID = @agentID, " +
"parentFolderID = @parentFolderID," + "parentFolderID = @parentFolderID," +
"folderName = @folderName," + "folderName = @folderName," +
"type = @type," + "type = @type," +
"version = @version where " + "version = @version where " +
"folderID = @keyFolderID;", database.getConnection()); "folderID = @keyFolderID;"))
{
SqlParameter param1 = new SqlParameter("@folderID", folder.ID.ToString()); SqlParameter param1 = new SqlParameter("@folderID", folder.ID.ToString());
SqlParameter param2 = new SqlParameter("@agentID", folder.Owner.ToString()); SqlParameter param2 = new SqlParameter("@agentID", folder.Owner.ToString());
SqlParameter param3 = new SqlParameter("@parentFolderID", folder.ParentID.ToString()); SqlParameter param3 = new SqlParameter("@parentFolderID", folder.ParentID.ToString());
@ -658,6 +638,7 @@ namespace OpenSim.Data.MSSQL
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
}
/// <summary> /// <summary>
/// Updates an inventory folder /// Updates an inventory folder
@ -665,9 +646,10 @@ namespace OpenSim.Data.MSSQL
/// <param name="folder">Folder to update</param> /// <param name="folder">Folder to update</param>
public void moveInventoryFolder(InventoryFolderBase folder) public void moveInventoryFolder(InventoryFolderBase folder)
{ {
SqlCommand command = new SqlCommand("UPDATE inventoryfolders set folderID = @folderID, " + using (IDbCommand command = database.Query("UPDATE inventoryfolders set folderID = @folderID, " +
"parentFolderID = @parentFolderID," + "parentFolderID = @parentFolderID," +
"folderID = @keyFolderID;", database.getConnection()); "folderID = @keyFolderID;"))
{
SqlParameter param1 = new SqlParameter("@folderID", folder.ID.ToString()); SqlParameter param1 = new SqlParameter("@folderID", folder.ID.ToString());
SqlParameter param2 = new SqlParameter("@parentFolderID", folder.ParentID.ToString()); SqlParameter param2 = new SqlParameter("@parentFolderID", folder.ParentID.ToString());
SqlParameter param3 = new SqlParameter("@keyFolderID", folder.ID.ToString()); SqlParameter param3 = new SqlParameter("@keyFolderID", folder.ID.ToString());
@ -684,6 +666,7 @@ namespace OpenSim.Data.MSSQL
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
}
/// <summary> /// <summary>
/// Append a list of all the child folders of a parent folder /// Append a list of all the child folders of a parent folder
@ -721,13 +704,13 @@ namespace OpenSim.Data.MSSQL
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["folderID"] = folderID.ToString(); param["folderID"] = folderID.ToString();
IDbCommand cmd = database.Query("DELETE FROM inventoryfolders WHERE folderID=@folderID", param); using (IDbCommand cmd = database.Query("DELETE FROM inventoryfolders WHERE folderID=@folderID", param))
{
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Dispose(); }
} }
catch (SqlException e) catch (SqlException e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -744,14 +727,14 @@ namespace OpenSim.Data.MSSQL
param["parentFolderID"] = folderID.ToString(); param["parentFolderID"] = folderID.ToString();
IDbCommand cmd = using (IDbCommand cmd =
database.Query("DELETE FROM inventoryitems WHERE parentFolderID=@parentFolderID", param); database.Query("DELETE FROM inventoryitems WHERE parentFolderID=@parentFolderID", param))
{
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Dispose(); }
} }
catch (SqlException e) catch (SqlException e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -762,7 +745,7 @@ namespace OpenSim.Data.MSSQL
/// <param name="folderId">Id of folder to delete</param> /// <param name="folderId">Id of folder to delete</param>
public void deleteInventoryFolder(LLUUID folderID) public void deleteInventoryFolder(LLUUID folderID)
{ {
lock (database) // lock (database)
{ {
List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID); List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID);

View File

@ -31,7 +31,7 @@ using System.Data;
namespace OpenSim.Data.MSSQL namespace OpenSim.Data.MSSQL
{ {
/// <summary> /// <summary>
/// An interface to the log database for MySQL /// An interface to the log database for MSSQL
/// </summary> /// </summary>
internal class MSSQLLogData : ILogData internal class MSSQLLogData : ILogData
{ {
@ -46,27 +46,28 @@ namespace OpenSim.Data.MSSQL
public void Initialise(string connect) public void Initialise(string connect)
{ {
// TODO: do something with the connect string // TODO: do something with the connect string
IniFile GridDataMySqlFile = new IniFile("mssql_connection.ini"); IniFile gridDataMSSqlFile = new IniFile("mssql_connection.ini");
string settingDataSource = GridDataMySqlFile.ParseFileReadValue("data_source"); string settingDataSource = gridDataMSSqlFile.ParseFileReadValue("data_source");
string settingInitialCatalog = GridDataMySqlFile.ParseFileReadValue("initial_catalog"); string settingInitialCatalog = gridDataMSSqlFile.ParseFileReadValue("initial_catalog");
string settingPersistSecurityInfo = GridDataMySqlFile.ParseFileReadValue("persist_security_info"); string settingPersistSecurityInfo = gridDataMSSqlFile.ParseFileReadValue("persist_security_info");
string settingUserId = GridDataMySqlFile.ParseFileReadValue("user_id"); string settingUserId = gridDataMSSqlFile.ParseFileReadValue("user_id");
string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); string settingPassword = gridDataMSSqlFile.ParseFileReadValue("password");
database = database =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
settingPassword); settingPassword);
IDbCommand cmd = database.Query("select top 1 * from logs", new Dictionary<string, string>()); using (IDbCommand cmd = database.Query("select top 1 * from logs", new Dictionary<string, string>()))
{
try try
{ {
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Dispose();
} }
catch catch
{ {
database.ExecuteResourceSql("Mssql-logs.sql"); database.ExecuteResourceSql("Mssql-logs.sql");
} }
}
} }
@ -88,7 +89,7 @@ namespace OpenSim.Data.MSSQL
} }
catch catch
{ {
database.Reconnect(); // it didn't log, don't worry about it
} }
} }

View File

@ -44,11 +44,6 @@ namespace OpenSim.Data.MSSQL
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The database connection object
/// </summary>
private IDbConnection dbcon;
/// <summary> /// <summary>
/// Connection string for ADO.net /// Connection string for ADO.net
/// </summary> /// </summary>
@ -57,11 +52,24 @@ namespace OpenSim.Data.MSSQL
public MSSQLManager(string dataSource, string initialCatalog, string persistSecurityInfo, string userId, public MSSQLManager(string dataSource, string initialCatalog, string persistSecurityInfo, string userId,
string password) string password)
{ {
connectionString = "Data Source=" + dataSource + ";Initial Catalog=" + initialCatalog + SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
";Persist Security Info=" + persistSecurityInfo + ";User ID=" + userId + ";Password=" +
password + ";"; builder.DataSource = dataSource;
dbcon = new SqlConnection(connectionString); builder.InitialCatalog = initialCatalog;
dbcon.Open(); builder.PersistSecurityInfo = Convert.ToBoolean(persistSecurityInfo);
builder.UserID = userId;
builder.Password = password;
builder.ApplicationName = Assembly.GetEntryAssembly().Location;
connectionString = builder.ToString();
}
private SqlConnection createConnection()
{
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
return conn;
} }
//private DataTable createRegionsTable() //private DataTable createRegionsTable()
@ -121,7 +129,7 @@ namespace OpenSim.Data.MSSQL
} }
/// <summary> /// <summary>
/// /// Define Table function
/// </summary> /// </summary>
/// <param name="dt"></param> /// <param name="dt"></param>
/// <returns></returns> /// <returns></returns>
@ -178,35 +186,11 @@ namespace OpenSim.Data.MSSQL
} }
} }
/// <summary>
/// Shuts down the database connection
/// </summary>
public void Close()
{
dbcon.Close();
dbcon = null;
}
/// <summary> private static readonly Dictionary<string, string> emptyDictionary = new Dictionary<string, string>();
/// Reconnects to the database internal AutoClosingSqlCommand Query(string sql)
/// </summary>
public void Reconnect()
{ {
lock (dbcon) return Query(sql, emptyDictionary);
{
try
{
// Close the DB connection
dbcon.Close();
// Try reopen it
dbcon = new SqlConnection(connectionString);
dbcon.Open();
}
catch (Exception e)
{
m_log.Error("Unable to reconnect to database " + e.ToString());
}
}
} }
/// <summary> /// <summary>
@ -215,18 +199,20 @@ namespace OpenSim.Data.MSSQL
/// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param> /// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
/// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param> /// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param>
/// <returns>A Sql DB Command</returns> /// <returns>A Sql DB Command</returns>
public IDbCommand Query(string sql, Dictionary<string, string> parameters) internal AutoClosingSqlCommand Query(string sql, Dictionary<string, string> parameters)
{ {
SqlCommand dbcommand = (SqlCommand)dbcon.CreateCommand(); SqlCommand dbcommand = createConnection().CreateCommand();
dbcommand.CommandText = sql; dbcommand.CommandText = sql;
foreach (KeyValuePair<string, string> param in parameters) foreach (KeyValuePair<string, string> param in parameters)
{ {
dbcommand.Parameters.AddWithValue(param.Key, param.Value); dbcommand.Parameters.AddWithValue(param.Key, param.Value);
} }
return (IDbCommand)dbcommand; return new AutoClosingSqlCommand(dbcommand);
} }
/// <summary> /// <summary>
/// Runs a database reader object and returns a region row /// Runs a database reader object and returns a region row
/// </summary> /// </summary>
@ -400,7 +386,6 @@ namespace OpenSim.Data.MSSQL
if (reader.Read()) if (reader.Read())
{ {
// Region Main // Region Main
asset = new AssetBase(); asset = new AssetBase();
asset.Data = (byte[])reader["data"]; asset.Data = (byte[])reader["data"];
asset.Description = (string)reader["description"]; asset.Description = (string)reader["description"];
@ -443,20 +428,21 @@ namespace OpenSim.Data.MSSQL
bool returnval = false; bool returnval = false;
using (IDbCommand result = Query(sql, parameters))
{
try try
{ {
IDbCommand result = Query(sql, parameters);
if (result.ExecuteNonQuery() == 1) if (result.ExecuteNonQuery() == 1)
returnval = true; returnval = true;
result.Dispose();
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return false; return false;
} }
}
return returnval; return returnval;
} }
@ -467,32 +453,24 @@ namespace OpenSim.Data.MSSQL
/// <param name="name">the ressource string</param> /// <param name="name">the ressource string</param>
public void ExecuteResourceSql(string name) public void ExecuteResourceSql(string name)
{ {
SqlCommand cmd = new SqlCommand(getResourceString(name), (SqlConnection)dbcon); using (IDbCommand cmd = Query(getResourceString(name), new Dictionary<string,string>()))
{
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Dispose(); }
} }
/// <summary>
///
/// </summary>
/// <returns>The actual SqlConnection</returns>
public SqlConnection getConnection()
{
return (SqlConnection)dbcon;
}
/// <summary> /// <summary>
/// Given a list of tables, return the version of the tables, as seen in the database /// Given a list of tables, return the version of the tables, as seen in the database
/// </summary> /// </summary>
/// <param name="tableList"></param> /// <param name="tableList"></param>
public void GetTableVersion(Dictionary<string, string> tableList) public void GetTableVersion(Dictionary<string, string> tableList)
{
lock (dbcon)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["dbname"] = dbcon.Database; param["dbname"] = new SqlConnectionStringBuilder(connectionString).InitialCatalog;
IDbCommand tablesCmd =
Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG=@dbname", param); using (IDbCommand tablesCmd =
Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG=@dbname", param))
using (IDataReader tables = tablesCmd.ExecuteReader()) using (IDataReader tables = tablesCmd.ExecuteReader())
{ {
while (tables.Read()) while (tables.Read())
@ -510,7 +488,7 @@ namespace OpenSim.Data.MSSQL
} }
tables.Close(); tables.Close();
} }
}
} }
/// <summary> /// <summary>
@ -546,7 +524,6 @@ namespace OpenSim.Data.MSSQL
// string dllName = module.Assembly.ManifestModule.Name; // string dllName = module.Assembly.ManifestModule.Name;
Version dllVersion = module.Assembly.GetName().Version; Version dllVersion = module.Assembly.GetName().Version;
return return
string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
dllVersion.Revision); dllVersion.Revision);

View File

@ -44,7 +44,7 @@ namespace OpenSim.Data.MSSQL
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// Database manager for MySQL /// Database manager for MSSQL
/// </summary> /// </summary>
public MSSQLManager database; public MSSQLManager database;
@ -100,9 +100,9 @@ namespace OpenSim.Data.MSSQL
/// <returns></returns> /// <returns></returns>
private bool TestTables() private bool TestTables()
{ {
IDbCommand cmd;
cmd = database.Query("select top 1 * from " + m_usersTableName, new Dictionary<string, string>()); using (IDbCommand cmd = database.Query("select top 1 * from " + m_usersTableName, new Dictionary<string, string>()))
{
try try
{ {
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
@ -111,8 +111,10 @@ namespace OpenSim.Data.MSSQL
{ {
database.ExecuteResourceSql("Mssql-users.sql"); database.ExecuteResourceSql("Mssql-users.sql");
} }
}
cmd = database.Query("select top 1 * from " + m_agentsTableName, new Dictionary<string, string>()); using (IDbCommand cmd = database.Query("select top 1 * from " + m_agentsTableName, new Dictionary<string, string>()))
{
try try
{ {
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
@ -121,8 +123,10 @@ namespace OpenSim.Data.MSSQL
{ {
database.ExecuteResourceSql("Mssql-agents.sql"); database.ExecuteResourceSql("Mssql-agents.sql");
} }
}
cmd = database.Query("select top 1 * from " + m_userFriendsTableName, new Dictionary<string, string>()); using (IDbCommand cmd = database.Query("select top 1 * from " + m_userFriendsTableName, new Dictionary<string, string>()))
{
try try
{ {
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
@ -131,6 +135,7 @@ namespace OpenSim.Data.MSSQL
{ {
database.ExecuteResourceSql("CreateUserFriendsTable.sql"); database.ExecuteResourceSql("CreateUserFriendsTable.sql");
} }
}
return true; return true;
} }
@ -144,28 +149,19 @@ namespace OpenSim.Data.MSSQL
override public UserProfileData GetUserByName(string user, string last) override public UserProfileData GetUserByName(string user, string last)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["first"] = user; param["first"] = user;
param["second"] = last; param["second"] = last;
IDbCommand result = using (IDbCommand result = database.Query("SELECT * FROM " + m_usersTableName + " WHERE username = @first AND lastname = @second", param))
database.Query("SELECT * FROM " + m_usersTableName + " WHERE username = @first AND lastname = @second", param); using (IDataReader reader = result.ExecuteReader())
IDataReader reader = result.ExecuteReader(); {
return database.readUserRow(reader);
UserProfileData row = database.readUserRow(reader);
reader.Close();
result.Dispose();
return row;
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
@ -191,32 +187,30 @@ namespace OpenSim.Data.MSSQL
try try
{ {
lock (database) using (IDbCommand adder =
{
IDbCommand adder =
database.Query( database.Query(
"INSERT INTO " + m_userFriendsTableName + " " + "INSERT INTO " + m_userFriendsTableName + " " +
"(ownerID,friendID,friendPerms,datetimestamp) " + "(ownerID,friendID,friendPerms,datetimestamp) " +
"VALUES " + "VALUES " +
"(@ownerID,@friendID,@friendPerms,@datetimestamp)", "(@ownerID,@friendID,@friendPerms,@datetimestamp)",
param); param))
{
adder.ExecuteNonQuery(); adder.ExecuteNonQuery();
}
adder = using (IDbCommand adder =
database.Query( database.Query(
"INSERT INTO " + m_userFriendsTableName + " " + "INSERT INTO " + m_userFriendsTableName + " " +
"(ownerID,friendID,friendPerms,datetimestamp) " + "(ownerID,friendID,friendPerms,datetimestamp) " +
"VALUES " + "VALUES " +
"(@friendID,@ownerID,@friendPerms,@datetimestamp)", "(@friendID,@ownerID,@friendPerms,@datetimestamp)",
param); param))
{
adder.ExecuteNonQuery(); adder.ExecuteNonQuery();
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return; return;
} }
@ -236,27 +230,26 @@ namespace OpenSim.Data.MSSQL
try try
{ {
lock (database) using (IDbCommand updater =
{
IDbCommand updater =
database.Query( database.Query(
"delete from " + m_userFriendsTableName + " where ownerID = @ownerID and friendID = @friendID", "delete from " + m_userFriendsTableName + " where ownerID = @ownerID and friendID = @friendID",
param); param))
{
updater.ExecuteNonQuery(); updater.ExecuteNonQuery();
}
updater = using (IDbCommand updater =
database.Query( database.Query(
"delete from " + m_userFriendsTableName + " where ownerID = @friendID and friendID = @ownerID", "delete from " + m_userFriendsTableName + " where ownerID = @friendID and friendID = @ownerID",
param); param))
{
updater.ExecuteNonQuery(); updater.ExecuteNonQuery();
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return;
} }
} }
@ -276,23 +269,19 @@ namespace OpenSim.Data.MSSQL
try try
{ {
lock (database) using (IDbCommand updater =
{
IDbCommand updater =
database.Query( database.Query(
"update " + m_userFriendsTableName + "update " + m_userFriendsTableName +
" SET friendPerms = @friendPerms " + " SET friendPerms = @friendPerms " +
"where ownerID = @ownerID and friendID = @friendID", "where ownerID = @ownerID and friendID = @friendID",
param); param))
{
updater.ExecuteNonQuery(); updater.ExecuteNonQuery();
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return;
} }
} }
@ -309,18 +298,15 @@ namespace OpenSim.Data.MSSQL
param["@ownerID"] = friendlistowner.UUID.ToString(); param["@ownerID"] = friendlistowner.UUID.ToString();
try try
{
lock (database)
{ {
//Left Join userfriends to itself //Left Join userfriends to itself
IDbCommand result = using (IDbCommand result =
database.Query( database.Query(
"select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " + m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" + "select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " + m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" +
" where a.ownerID = @ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID", " where a.ownerID = @ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID",
param); param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
while (reader.Read()) while (reader.Read())
{ {
FriendListItem fli = new FriendListItem(); FriendListItem fli = new FriendListItem();
@ -333,15 +319,11 @@ namespace OpenSim.Data.MSSQL
Lfli.Add(fli); Lfli.Add(fli);
} }
reader.Close();
result.Dispose();
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return Lfli;
} }
return Lfli; return Lfli;
@ -374,20 +356,14 @@ namespace OpenSim.Data.MSSQL
if (querysplit.Length == 2) if (querysplit.Length == 2)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["first"] = querysplit[0]; param["first"] = querysplit[0];
param["second"] = querysplit[1]; param["second"] = querysplit[1];
IDbCommand result = using (IDbCommand result = database.Query("SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username = @first AND lastname = @second", param))
database.Query( using (IDataReader reader = result.ExecuteReader())
"SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username = @first AND lastname = @second", {
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read()) while (reader.Read())
{ {
AvatarPickerAvatar user = new AvatarPickerAvatar(); AvatarPickerAvatar user = new AvatarPickerAvatar();
@ -396,33 +372,23 @@ namespace OpenSim.Data.MSSQL
user.lastName = (string)reader["lastname"]; user.lastName = (string)reader["lastname"];
returnlist.Add(user); returnlist.Add(user);
} }
reader.Close();
result.Dispose();
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return returnlist;
} }
} }
else if (querysplit.Length == 1) else if (querysplit.Length == 1)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["first"] = querysplit[0]; param["first"] = querysplit[0];
IDbCommand result = using (IDbCommand result = database.Query("SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username = @first OR lastname = @first", param))
database.Query( using (IDataReader reader = result.ExecuteReader())
"SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username = @first OR lastname = @first", {
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read()) while (reader.Read())
{ {
AvatarPickerAvatar user = new AvatarPickerAvatar(); AvatarPickerAvatar user = new AvatarPickerAvatar();
@ -431,15 +397,11 @@ namespace OpenSim.Data.MSSQL
user.lastName = (string)reader["lastname"]; user.lastName = (string)reader["lastname"];
returnlist.Add(user); returnlist.Add(user);
} }
reader.Close();
result.Dispose();
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return returnlist;
} }
} }
return returnlist; return returnlist;
@ -453,26 +415,18 @@ namespace OpenSim.Data.MSSQL
override public UserProfileData GetUserByUUID(LLUUID uuid) override public UserProfileData GetUserByUUID(LLUUID uuid)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["uuid"] = uuid.ToString(); param["uuid"] = uuid.ToString();
IDbCommand result = database.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = @uuid", param); using (IDbCommand result = database.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = @uuid", param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
UserProfileData row = database.readUserRow(reader); return database.readUserRow(reader);
reader.Close();
result.Dispose();
return row;
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
@ -508,26 +462,18 @@ namespace OpenSim.Data.MSSQL
override public UserAgentData GetAgentByUUID(LLUUID uuid) override public UserAgentData GetAgentByUUID(LLUUID uuid)
{ {
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["uuid"] = uuid.ToString(); param["uuid"] = uuid.ToString();
IDbCommand result = database.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = @uuid", param); using (IDbCommand result = database.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = @uuid", param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
UserAgentData row = database.readAgentRow(reader); return database.readAgentRow(reader);
reader.Close();
result.Dispose();
return row;
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
@ -553,8 +499,6 @@ namespace OpenSim.Data.MSSQL
override public void AddNewUserProfile(UserProfileData user) override public void AddNewUserProfile(UserProfileData user)
{ {
try try
{
lock (database)
{ {
InsertUserRow(user.ID, user.FirstName, user.SurName, user.PasswordHash, user.PasswordSalt, InsertUserRow(user.ID, user.FirstName, user.SurName, user.PasswordHash, user.PasswordSalt,
user.HomeRegion, user.HomeLocation.X, user.HomeLocation.Y, user.HomeRegion, user.HomeLocation.X, user.HomeLocation.Y,
@ -565,10 +509,8 @@ namespace OpenSim.Data.MSSQL
user.AboutText, user.FirstLifeAboutText, user.Image, user.AboutText, user.FirstLifeAboutText, user.Image,
user.FirstLifeImage, user.WebLoginKey); user.FirstLifeImage, user.WebLoginKey);
} }
}
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -646,16 +588,13 @@ namespace OpenSim.Data.MSSQL
parameters["profileFirstImage"] = firstImage.ToString(); parameters["profileFirstImage"] = firstImage.ToString();
parameters["webLoginKey"] = LLUUID.Random().ToString(); parameters["webLoginKey"] = LLUUID.Random().ToString();
bool returnval = false;
try try
{ {
IDbCommand result = database.Query(sql, parameters); using (IDbCommand result = database.Query(sql, parameters))
{
if (result.ExecuteNonQuery() == 1) return (result.ExecuteNonQuery() == 1);
returnval = true; }
result.Dispose();
} }
catch (Exception e) catch (Exception e)
{ {
@ -663,7 +602,6 @@ namespace OpenSim.Data.MSSQL
return false; return false;
} }
return returnval;
} }
/// <summary> /// <summary>
@ -682,7 +620,7 @@ namespace OpenSim.Data.MSSQL
/// <returns></returns> /// <returns></returns>
override public bool UpdateUserProfile(UserProfileData user) override public bool UpdateUserProfile(UserProfileData user)
{ {
SqlCommand command = new SqlCommand("UPDATE " + m_usersTableName + " set UUID = @uuid, " + using (IDbCommand command = database.Query("UPDATE " + m_usersTableName + " set UUID = @uuid, " +
"username = @username, " + "username = @username, " +
"lastname = @lastname," + "lastname = @lastname," +
"passwordHash = @passwordHash," + "passwordHash = @passwordHash," +
@ -705,7 +643,8 @@ namespace OpenSim.Data.MSSQL
"profileImage = @profileImage," + "profileImage = @profileImage," +
"profileFirstImage = @profileFirstImage, " + "profileFirstImage = @profileFirstImage, " +
"webLoginKey = @webLoginKey where " + "webLoginKey = @webLoginKey where " +
"UUID = @keyUUUID;", database.getConnection()); "UUID = @keyUUUID;"))
{
SqlParameter param1 = new SqlParameter("@uuid", user.ID.ToString()); SqlParameter param1 = new SqlParameter("@uuid", user.ID.ToString());
SqlParameter param2 = new SqlParameter("@username", user.FirstName); SqlParameter param2 = new SqlParameter("@username", user.FirstName);
SqlParameter param3 = new SqlParameter("@lastname", user.SurName); SqlParameter param3 = new SqlParameter("@lastname", user.SurName);
@ -757,19 +696,13 @@ namespace OpenSim.Data.MSSQL
try try
{ {
int affected = command.ExecuteNonQuery(); int affected = command.ExecuteNonQuery();
if (affected != 0) return (affected != 0);
{
return true;
}
else
{
return false;
}
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
}
return false; return false;
} }
@ -804,29 +737,22 @@ namespace OpenSim.Data.MSSQL
{ {
// return new AvatarAppearance(); // return new AvatarAppearance();
try try
{
lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["@UUID"] = user.ToString(); param["@UUID"] = user.ToString();
IDbCommand result = using (IDbCommand result =
database.Query("SELECT * FROM avatarappearance WHERE owner = @UUID", param); database.Query("SELECT * FROM avatarappearance WHERE owner = @UUID", param))
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
AvatarAppearance item = null; AvatarAppearance item = null;
if (reader.Read()) if (reader.Read())
item = readUserAppearance(reader); item = readUserAppearance(reader);
reader.Close();
result.Dispose();
return item; return item;
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
return null; return null;
@ -906,7 +832,8 @@ namespace OpenSim.Data.MSSQL
sql += "@jacket_item, @jacket_asset, @gloves_item, @gloves_asset, @undershirt_item, @undershirt_asset, @underpants_item, @underpants_asset, "; sql += "@jacket_item, @jacket_asset, @gloves_item, @gloves_asset, @undershirt_item, @undershirt_asset, @underpants_item, @underpants_asset, ";
sql += "@skirt_item, @skirt_asset)"; sql += "@skirt_item, @skirt_asset)";
SqlCommand cmd = new SqlCommand(sql, database.getConnection()); using (AutoClosingSqlCommand cmd = database.Query(sql))
{
cmd.Parameters.AddWithValue("@owner", appearance.Owner.ToString()); cmd.Parameters.AddWithValue("@owner", appearance.Owner.ToString());
cmd.Parameters.AddWithValue("@serial", appearance.Serial); cmd.Parameters.AddWithValue("@serial", appearance.Serial);
cmd.Parameters.AddWithValue("@visual_params", appearance.VisualParams); cmd.Parameters.AddWithValue("@visual_params", appearance.VisualParams);
@ -942,13 +869,12 @@ namespace OpenSim.Data.MSSQL
try try
{ {
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Dispose();
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
return; }
} }
/// <summary> /// <summary>
@ -958,7 +884,7 @@ namespace OpenSim.Data.MSSQL
/// <param name="item">the item UUID</param> /// <param name="item">the item UUID</param>
override public void AddAttachment(LLUUID user, LLUUID item) override public void AddAttachment(LLUUID user, LLUUID item)
{ {
return; // TBI?
} }
/// <summary> /// <summary>
@ -968,7 +894,7 @@ namespace OpenSim.Data.MSSQL
/// <param name="item">the item UUID</param> /// <param name="item">the item UUID</param>
override public void RemoveAttachment(LLUUID user, LLUUID item) override public void RemoveAttachment(LLUUID user, LLUUID item)
{ {
return; // TBI?
} }
/// <summary> /// <summary>