From c52c68f314c67c76c7181a6d0828f476290fbd66 Mon Sep 17 00:00:00 2001 From: Sean Dague Date: Wed, 2 Apr 2008 15:24:31 +0000 Subject: whole lot more moving --- OpenSim/Data/MSSQL/MSSQLAssetData.cs | 221 +++ OpenSim/Data/MSSQL/MSSQLDataStore.cs | 1622 ++++++++++++++++++++ OpenSim/Data/MSSQL/MSSQLGridData.cs | 366 +++++ OpenSim/Data/MSSQL/MSSQLInventoryData.cs | 728 +++++++++ OpenSim/Data/MSSQL/MSSQLLogData.cs | 120 ++ OpenSim/Data/MSSQL/MSSQLManager.cs | 529 +++++++ OpenSim/Data/MSSQL/MSSQLUserData.cs | 771 ++++++++++ OpenSim/Data/MSSQL/Properties/AssemblyInfo.cs | 65 + OpenSim/Data/MSSQL/Resources/AvatarAppearance.sql | 44 + OpenSim/Data/MSSQL/Resources/CreateAssetsTable.sql | 19 + .../Data/MSSQL/Resources/CreateFoldersTable.sql | 27 + OpenSim/Data/MSSQL/Resources/CreateItemsTable.sql | 39 + .../MSSQL/Resources/CreateUserFriendsTable.sql | 14 + OpenSim/Data/MSSQL/Resources/Mssql-agents.sql | 37 + OpenSim/Data/MSSQL/Resources/Mssql-logs.sql | 20 + OpenSim/Data/MSSQL/Resources/Mssql-regions.sql | 41 + OpenSim/Data/MSSQL/Resources/Mssql-users.sql | 42 + 17 files changed, 4705 insertions(+) create mode 100644 OpenSim/Data/MSSQL/MSSQLAssetData.cs create mode 100644 OpenSim/Data/MSSQL/MSSQLDataStore.cs create mode 100644 OpenSim/Data/MSSQL/MSSQLGridData.cs create mode 100644 OpenSim/Data/MSSQL/MSSQLInventoryData.cs create mode 100644 OpenSim/Data/MSSQL/MSSQLLogData.cs create mode 100644 OpenSim/Data/MSSQL/MSSQLManager.cs create mode 100644 OpenSim/Data/MSSQL/MSSQLUserData.cs create mode 100644 OpenSim/Data/MSSQL/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Data/MSSQL/Resources/AvatarAppearance.sql create mode 100644 OpenSim/Data/MSSQL/Resources/CreateAssetsTable.sql create mode 100644 OpenSim/Data/MSSQL/Resources/CreateFoldersTable.sql create mode 100644 OpenSim/Data/MSSQL/Resources/CreateItemsTable.sql create mode 100644 OpenSim/Data/MSSQL/Resources/CreateUserFriendsTable.sql create mode 100644 OpenSim/Data/MSSQL/Resources/Mssql-agents.sql create mode 100644 OpenSim/Data/MSSQL/Resources/Mssql-logs.sql create mode 100644 OpenSim/Data/MSSQL/Resources/Mssql-regions.sql create mode 100644 OpenSim/Data/MSSQL/Resources/Mssql-users.sql (limited to 'OpenSim/Data/MSSQL') diff --git a/OpenSim/Data/MSSQL/MSSQLAssetData.cs b/OpenSim/Data/MSSQL/MSSQLAssetData.cs new file mode 100644 index 0000000..059bb5e --- /dev/null +++ b/OpenSim/Data/MSSQL/MSSQLAssetData.cs @@ -0,0 +1,221 @@ +/* + * 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.Data; +using System.Data.SqlClient; +using libsecondlife; +using OpenSim.Framework.Console; + +namespace OpenSim.Framework.Data.MSSQL +{ + internal class MSSQLAssetData : AssetDataBase + { + private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + private MSSQLManager database; + + #region IAssetProvider Members + + private void UpgradeAssetsTable(string tableName) + { + // null as the version, indicates that the table didn't exist + if (tableName == null) + { + m_log.Info("[ASSETS]: Creating new database tables"); + database.ExecuteResourceSql("CreateAssetsTable.sql"); + return; + } + } + + /// + /// Ensure that the assets related tables exists and are at the latest version + /// + private void TestTables() + { + Dictionary tableList = new Dictionary(); + + tableList["assets"] = null; + database.GetTableVersion(tableList); + + UpgradeAssetsTable(tableList["assets"]); + } + + override public AssetBase FetchAsset(LLUUID assetID) + { + AssetBase asset = null; + + Dictionary param = new Dictionary(); + param["id"] = assetID.ToString(); + + IDbCommand result = database.Query("SELECT * FROM assets WHERE id = @id", param); + IDataReader reader = result.ExecuteReader(); + + asset = database.getAssetRow(reader); + reader.Close(); + result.Dispose(); + + return asset; + } + + override public void CreateAsset(AssetBase asset) + { + if (ExistsAsset((LLUUID) asset.FullID)) + { + return; + } + + + SqlCommand cmd = + new SqlCommand( + "INSERT INTO assets ([id], [name], [description], [assetType], [invType], [local], [temporary], [data])" + + " VALUES " + + "(@id, @name, @description, @assetType, @invType, @local, @temporary, @data)", + database.getConnection()); + + using (cmd) + { + //SqlParameter p = cmd.Parameters.Add("id", SqlDbType.NVarChar); + //p.Value = asset.FullID.ToString(); + cmd.Parameters.AddWithValue("id", asset.FullID.ToString()); + cmd.Parameters.AddWithValue("name", asset.Name); + cmd.Parameters.AddWithValue("description", asset.Description); + SqlParameter e = cmd.Parameters.Add("assetType", SqlDbType.TinyInt); + e.Value = asset.Type; + SqlParameter f = cmd.Parameters.Add("invType", SqlDbType.TinyInt); + f.Value = asset.InvType; + SqlParameter g = cmd.Parameters.Add("local", SqlDbType.TinyInt); + g.Value = asset.Local; + SqlParameter h = cmd.Parameters.Add("temporary", SqlDbType.TinyInt); + h.Value = asset.Temporary; + SqlParameter i = cmd.Parameters.Add("data", SqlDbType.Image); + i.Value = asset.Data; + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception) + { + throw; + } + + cmd.Dispose(); + } + } + + + override public void UpdateAsset(AssetBase asset) + { + SqlCommand command = new SqlCommand("UPDATE assets set id = @id, " + + "name = @name, " + + "description = @description," + + "assetType = @assetType," + + "invType = @invType," + + "local = @local," + + "temporary = @temporary," + + "data = @data where " + + "id = @keyId;", database.getConnection()); + SqlParameter param1 = new SqlParameter("@id", asset.FullID.ToString()); + SqlParameter param2 = new SqlParameter("@name", asset.Name); + SqlParameter param3 = new SqlParameter("@description", asset.Description); + SqlParameter param4 = new SqlParameter("@assetType", asset.Type); + SqlParameter param5 = new SqlParameter("@invType", asset.InvType); + SqlParameter param6 = new SqlParameter("@local", asset.Local); + SqlParameter param7 = new SqlParameter("@temporary", asset.Temporary); + SqlParameter param8 = new SqlParameter("@data", asset.Data); + SqlParameter param9 = new SqlParameter("@keyId", asset.FullID.ToString()); + command.Parameters.Add(param1); + command.Parameters.Add(param2); + command.Parameters.Add(param3); + command.Parameters.Add(param4); + command.Parameters.Add(param5); + command.Parameters.Add(param6); + command.Parameters.Add(param7); + command.Parameters.Add(param8); + command.Parameters.Add(param9); + + try + { + command.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.Error(e.ToString()); + } + } + + override public bool ExistsAsset(LLUUID uuid) + { + if (FetchAsset(uuid) != null) + { + return true; + } + return false; + } + + /// + /// All writes are immediately commited to the database, so this is a no-op + /// + override public void CommitAssets() + { + } + + #endregion + + #region IPlugin Members + + override public void Initialise() + { + IniFile GridDataMySqlFile = new IniFile("mssql_connection.ini"); + string settingDataSource = GridDataMySqlFile.ParseFileReadValue("data_source"); + string settingInitialCatalog = GridDataMySqlFile.ParseFileReadValue("initial_catalog"); + string settingPersistSecurityInfo = GridDataMySqlFile.ParseFileReadValue("persist_security_info"); + string settingUserId = GridDataMySqlFile.ParseFileReadValue("user_id"); + string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); + + database = + new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, + settingPassword); + + TestTables(); + } + + override public string Version + { +// get { return database.getVersion(); } + get { return database.getVersion(); } + } + + override public string Name + { + get { return "MSSQL Asset storage engine"; } + } + + #endregion + } +} diff --git a/OpenSim/Data/MSSQL/MSSQLDataStore.cs b/OpenSim/Data/MSSQL/MSSQLDataStore.cs new file mode 100644 index 0000000..d34abe3 --- /dev/null +++ b/OpenSim/Data/MSSQL/MSSQLDataStore.cs @@ -0,0 +1,1622 @@ +/* + * 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.Data; +using System.Data.SqlClient; +using System.IO; +using libsecondlife; +using OpenSim.Framework; +using OpenSim.Framework.Console; +using OpenSim.Framework.Data; +using OpenSim.Region.Environment.Interfaces; +using OpenSim.Region.Environment.Scenes; +using OpenSim.Framework.Data.MSSQL; + +namespace OpenSim.Framework.Data.MSSQL +{ + public class MSSQLDataStore : IRegionDataStore + { + // private static FileSystemDataStore Instance = new FileSystemDataStore(); + private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + private const string m_primSelect = "select * from prims"; + private const string m_shapeSelect = "select * from primshapes"; + private const string m_itemsSelect = "select * from primitems"; + private const string m_terrainSelect = "select top 1 * from terrain"; + private const string m_landSelect = "select * from land"; + private const string m_landAccessListSelect = "select * from landaccesslist"; + + private DataSet m_dataSet; + private SqlDataAdapter m_primDataAdapter; + private SqlDataAdapter m_shapeDataAdapter; + private SqlDataAdapter m_itemsDataAdapter; + private SqlConnection m_connection; + private SqlDataAdapter m_terrainDataAdapter; + private SqlDataAdapter m_landDataAdapter; + private SqlDataAdapter m_landAccessListDataAdapter; + + private DataTable m_primTable; + private DataTable m_shapeTable; + private DataTable m_itemsTable; + private DataTable m_terrainTable; + private DataTable m_landTable; + private DataTable m_landAccessListTable; + + // Temporary attribute while this is experimental + private bool persistPrimInventories; + + /*********************************************************************** + * + * Public Interface Functions + * + **********************************************************************/ + + // see IRegionDataStore + public void Initialise(string connectionString, bool persistPrimInventories) + { + // Instance.Initialise("", true); + + m_dataSet = new DataSet(); + this.persistPrimInventories = persistPrimInventories; + + m_log.Info("[DATASTORE]: MSSql - connecting: " + connectionString); + m_connection = new SqlConnection(connectionString); + + SqlCommand primSelectCmd = new SqlCommand(m_primSelect, m_connection); + m_primDataAdapter = new SqlDataAdapter(primSelectCmd); + + SqlCommand shapeSelectCmd = new SqlCommand(m_shapeSelect, m_connection); + m_shapeDataAdapter = new SqlDataAdapter(shapeSelectCmd); + + SqlCommand itemsSelectCmd = new SqlCommand(m_itemsSelect, m_connection); + m_itemsDataAdapter = new SqlDataAdapter(itemsSelectCmd); + + SqlCommand terrainSelectCmd = new SqlCommand(m_terrainSelect, m_connection); + m_terrainDataAdapter = new SqlDataAdapter(terrainSelectCmd); + + SqlCommand landSelectCmd = new SqlCommand(m_landSelect, m_connection); + m_landDataAdapter = new SqlDataAdapter(landSelectCmd); + + SqlCommand landAccessListSelectCmd = new SqlCommand(m_landAccessListSelect, m_connection); + m_landAccessListDataAdapter = new SqlDataAdapter(landAccessListSelectCmd); + + TestTables(m_connection); + + lock (m_dataSet) + { + m_primTable = createPrimTable(); + m_dataSet.Tables.Add(m_primTable); + setupPrimCommands(m_primDataAdapter, m_connection); + m_primDataAdapter.Fill(m_primTable); + + m_shapeTable = createShapeTable(); + m_dataSet.Tables.Add(m_shapeTable); + setupShapeCommands(m_shapeDataAdapter, m_connection); + m_shapeDataAdapter.Fill(m_shapeTable); + + if (persistPrimInventories) + { + m_itemsTable = createItemsTable(); + m_dataSet.Tables.Add(m_itemsTable); + SetupItemsCommands(m_itemsDataAdapter, m_connection); + m_itemsDataAdapter.Fill(m_itemsTable); + } + + m_terrainTable = createTerrainTable(); + m_dataSet.Tables.Add(m_terrainTable); + setupTerrainCommands(m_terrainDataAdapter, m_connection); + m_terrainDataAdapter.Fill(m_terrainTable); + + m_landTable = createLandTable(); + m_dataSet.Tables.Add(m_landTable); + setupLandCommands(m_landDataAdapter, m_connection); + m_landDataAdapter.Fill(m_landTable); + + m_landAccessListTable = createLandAccessListTable(); + m_dataSet.Tables.Add(m_landAccessListTable); + setupLandAccessCommands(m_landAccessListDataAdapter, m_connection); + m_landAccessListDataAdapter.Fill(m_landAccessListTable); + } + } + + public void StoreObject(SceneObjectGroup obj, LLUUID regionUUID) + { + // Instance.StoreObject(obj, regionUUID); + + lock (m_dataSet) + { + foreach (SceneObjectPart prim in obj.Children.Values) + { + if ((prim.ObjectFlags & (uint)LLObject.ObjectFlags.Physics) == 0) + { + m_log.Info("[DATASTORE]: Adding obj: " + obj.UUID + " to region: " + regionUUID); + addPrim(prim, obj.UUID, regionUUID); + } + else + { + // m_log.Info("[DATASTORE]: Ignoring Physical obj: " + obj.UUID + " in region: " + regionUUID); + } + } + } + + Commit(); + } + + public void RemoveObject(LLUUID obj, LLUUID regionUUID) + { + // Instance.RemoveObject(obj, regionUUID); + + m_log.InfoFormat("[DATASTORE]: Removing obj: {0} from region: {1}", obj.UUID, regionUUID); + + DataTable prims = m_primTable; + DataTable shapes = m_shapeTable; + + string selectExp = "SceneGroupID = '" + obj.ToString() + "'"; + lock (m_dataSet) + { + foreach (DataRow row in prims.Select(selectExp)) + { + // Remove shapes row + LLUUID uuid = new LLUUID((string)row["UUID"]); + + DataRow shapeRow = shapes.Rows.Find(uuid.UUID); + if (shapeRow != null) + { + shapeRow.Delete(); + } + + if (persistPrimInventories) + { + RemoveItems(new LLUUID((string)row["UUID"])); + } + + // Remove prim row + row.Delete(); + } + } + + Commit(); + } + + /// + /// Remove all persisted items of the given prim. + /// The caller must acquire the necessrary synchronization locks and commit or rollback changes. + /// + private void RemoveItems(LLUUID uuid) + { + String sql = String.Format("primID = '{0}'", uuid); + DataRow[] itemRows = m_itemsTable.Select(sql); + + foreach (DataRow itemRow in itemRows) + { + itemRow.Delete(); + } + } + + /// + /// Load persisted objects from region storage. + /// + public List LoadObjects(LLUUID regionUUID) + { + // return Instance.LoadObjects(regionUUID); + + Dictionary createdObjects = new Dictionary(); + + List retvals = new List(); + + DataTable prims = m_primTable; + DataTable shapes = m_shapeTable; + + string byRegion = "RegionUUID = '" + regionUUID.ToString() + "'"; + string orderByParent = "ParentID ASC"; + + lock (m_dataSet) + { + DataRow[] primsForRegion = prims.Select(byRegion, orderByParent); + m_log.Info("[DATASTORE]: " + + "Loaded " + primsForRegion.Length + " prims for region: " + regionUUID); + + foreach (DataRow primRow in primsForRegion) + { + try + { + string uuid = (string)primRow["UUID"]; + string objID = (string)primRow["SceneGroupID"]; + + SceneObjectPart prim = buildPrim(primRow); + + if (uuid == objID) //is new SceneObjectGroup ? + { + SceneObjectGroup group = new SceneObjectGroup(); + + DataRow shapeRow = shapes.Rows.Find(prim.UUID); + if (shapeRow != null) + { + prim.Shape = buildShape(shapeRow); + } + else + { + m_log.Info( + "No shape found for prim in storage, so setting default box shape"); + prim.Shape = PrimitiveBaseShape.Default; + } + group.AddPart(prim); + group.RootPart = prim; + + createdObjects.Add(group.UUID, group); + retvals.Add(group); + } + else + { + DataRow shapeRow = shapes.Rows.Find(prim.UUID); + if (shapeRow != null) + { + prim.Shape = buildShape(shapeRow); + } + else + { + m_log.Info( + "No shape found for prim in storage, so setting default box shape"); + prim.Shape = PrimitiveBaseShape.Default; + } + createdObjects[new LLUUID(objID)].AddPart(prim); + } + + if (persistPrimInventories) + { + LoadItems(prim); + } + } + catch (Exception e) + { + m_log.Error("[DATASTORE]: Failed create prim object, exception and data follows"); + m_log.Info("[DATASTORE]: " + e.ToString()); + foreach (DataColumn col in prims.Columns) + { + m_log.Info("[DATASTORE]: Col: " + col.ColumnName + " => " + primRow[col]); + } + } + } + } + return retvals; + } + + /// + /// Load in a prim's persisted inventory. + /// + /// + private void LoadItems(SceneObjectPart prim) + { + //m_log.InfoFormat("[DATASTORE]: Loading inventory for {0}, {1}", prim.Name, prim.UUID); + + DataTable dbItems = m_itemsTable; + + String sql = String.Format("primID = '{0}'", prim.UUID.ToString()); + DataRow[] dbItemRows = dbItems.Select(sql); + + IList inventory = new List(); + + foreach (DataRow row in dbItemRows) + { + TaskInventoryItem item = buildItem(row); + inventory.Add(item); + + //m_log.DebugFormat("[DATASTORE]: Restored item {0}, {1}", item.Name, item.ItemID); + } + + prim.RestoreInventoryItems(inventory); + + // XXX A nasty little hack to recover the folder id for the prim (which is currently stored in + // every item). This data should really be stored in the prim table itself. + if (dbItemRows.Length > 0) + { + prim.FolderID = inventory[0].ParentID; + } + } + + public void StoreTerrain(double[,] ter, LLUUID regionID) + { + int revision = Util.UnixTimeSinceEpoch(); + m_log.Info("[DATASTORE]: Storing terrain revision r" + revision.ToString()); + + DataTable terrain = m_dataSet.Tables["terrain"]; + lock (m_dataSet) + { + SqlCommand cmd = new SqlCommand("insert into terrain(RegionUUID, Revision, Heightfield)" + + " values(@RegionUUID, @Revision, @Heightfield)", m_connection); + using (cmd) + { + cmd.Parameters.Add(new SqlParameter("@RegionUUID", regionID.UUID)); + cmd.Parameters.Add(new SqlParameter("@Revision", revision)); + cmd.Parameters.Add(new SqlParameter("@Heightfield", serializeTerrain(ter))); + cmd.ExecuteNonQuery(); + } + } + } + + public double[,] LoadTerrain(LLUUID regionID) + { + double[,] terret = new double[256, 256]; + terret.Initialize(); + + SqlCommand cmd = new SqlCommand( + @"select top 1 RegionUUID, Revision, Heightfield from terrain + where RegionUUID=@RegionUUID order by Revision desc" + , m_connection); + + SqlParameter param = new SqlParameter(); + cmd.Parameters.Add(new SqlParameter("@RegionUUID", regionID.UUID)); + + if (m_connection.State != ConnectionState.Open) + { + m_connection.Open(); + } + + using (SqlDataReader row = cmd.ExecuteReader()) + { + int rev = 0; + if (row.Read()) + { + MemoryStream str = new MemoryStream((byte[])row["Heightfield"]); + BinaryReader br = new BinaryReader(str); + for (int x = 0; x < 256; x++) + { + for (int y = 0; y < 256; y++) + { + terret[x, y] = br.ReadDouble(); + } + } + rev = (int)row["Revision"]; + } + else + { + m_log.Info("[DATASTORE]: No terrain found for region"); + return null; + } + + m_log.Info("[DATASTORE]: Loaded terrain revision r" + rev.ToString()); + } + + return terret; + } + + public void RemoveLandObject(LLUUID globalID) + { + // Instance.RemoveLandObject(globalID); + + lock (m_dataSet) + { + using (SqlCommand cmd = new SqlCommand("delete from land where UUID=@UUID", m_connection)) + { + cmd.Parameters.Add(new SqlParameter("@UUID", globalID.UUID)); + cmd.ExecuteNonQuery(); + } + + using ( + SqlCommand cmd = new SqlCommand("delete from landaccesslist where LandUUID=@UUID", m_connection) + ) + { + cmd.Parameters.Add(new SqlParameter("@UUID", globalID.UUID)); + cmd.ExecuteNonQuery(); + } + } + } + + public void StoreLandObject(ILandObject parcel) + { + // Instance.StoreLandObject(parcel, regionUUID); + + // Does the new locking fix it? + // m_log.Info("[DATASTORE]: Tedds temp fix: Waiting 3 seconds to avoid others writing to table while we hold a dataset of it. (Someone please fix! :))"); + // System.Threading.Thread.Sleep(2500 + rnd.Next(0, 1000)); + + lock (m_dataSet) + { + DataTable land = m_landTable; + DataTable landaccesslist = m_landAccessListTable; + + DataRow landRow = land.Rows.Find(parcel.landData.globalID.UUID); + if (landRow == null) + { + landRow = land.NewRow(); + fillLandRow(landRow, parcel.landData, parcel.regionUUID); + land.Rows.Add(landRow); + } + else + { + fillLandRow(landRow, parcel.landData, parcel.regionUUID); + } + + using ( + SqlCommand cmd = + new SqlCommand("delete from landaccesslist where LandUUID=@LandUUID", m_connection)) + { + cmd.Parameters.Add(new SqlParameter("@LandUUID", parcel.landData.globalID.UUID)); + cmd.ExecuteNonQuery(); + } + + foreach (ParcelManager.ParcelAccessEntry entry in parcel.landData.parcelAccessList) + { + DataRow newAccessRow = landaccesslist.NewRow(); + fillLandAccessRow(newAccessRow, entry, parcel.landData.globalID); + landaccesslist.Rows.Add(newAccessRow); + } + + } + Commit(); + } + + public List LoadLandObjects(LLUUID regionUUID) + { + List landDataForRegion = new List(); + lock (m_dataSet) + { + DataTable land = m_landTable; + DataTable landaccesslist = m_landAccessListTable; + string searchExp = "RegionUUID = '" + regionUUID.UUID + "'"; + DataRow[] rawDataForRegion = land.Select(searchExp); + foreach (DataRow rawDataLand in rawDataForRegion) + { + LandData newLand = buildLandData(rawDataLand); + string accessListSearchExp = "LandUUID = '" + newLand.globalID.UUID + "'"; + DataRow[] rawDataForLandAccessList = landaccesslist.Select(accessListSearchExp); + foreach (DataRow rawDataLandAccess in rawDataForLandAccessList) + { + newLand.parcelAccessList.Add(buildLandAccessData(rawDataLandAccess)); + } + + landDataForRegion.Add(newLand); + } + } + return landDataForRegion; + } + + public void Commit() + { + if (m_connection.State != ConnectionState.Open) + { + m_connection.Open(); + } + + lock (m_dataSet) + { + // DisplayDataSet(m_dataSet, "Region DataSet"); + + m_primDataAdapter.Update(m_primTable); + m_shapeDataAdapter.Update(m_shapeTable); + + if (persistPrimInventories) + { + m_itemsDataAdapter.Update(m_itemsTable); + } + + m_terrainDataAdapter.Update(m_terrainTable); + m_landDataAdapter.Update(m_landTable); + m_landAccessListDataAdapter.Update(m_landAccessListTable); + + m_dataSet.AcceptChanges(); + } + } + + public void Shutdown() + { + Commit(); + } + + /*********************************************************************** + * + * Database Definition Functions + * + * This should be db agnostic as we define them in ADO.NET terms + * + **********************************************************************/ + + private DataColumn createCol(DataTable dt, string name, Type type) + { + DataColumn col = new DataColumn(name, type); + dt.Columns.Add(col); + return col; + } + + private DataTable createTerrainTable() + { + DataTable terrain = new DataTable("terrain"); + + createCol(terrain, "RegionUUID", typeof(String)); + createCol(terrain, "Revision", typeof(Int32)); + createCol(terrain, "Heightfield", typeof(Byte[])); + + return terrain; + } + + private DataTable createPrimTable() + { + DataTable prims = new DataTable("prims"); + + createCol(prims, "UUID", typeof(String)); + createCol(prims, "RegionUUID", typeof(String)); + createCol(prims, "ParentID", typeof(Int32)); + createCol(prims, "CreationDate", typeof(Int32)); + createCol(prims, "Name", typeof(String)); + createCol(prims, "SceneGroupID", typeof(String)); + // various text fields + createCol(prims, "Text", typeof(String)); + createCol(prims, "Description", typeof(String)); + createCol(prims, "SitName", typeof(String)); + createCol(prims, "TouchName", typeof(String)); + // permissions + createCol(prims, "ObjectFlags", typeof(Int32)); + createCol(prims, "CreatorID", typeof(String)); + createCol(prims, "OwnerID", typeof(String)); + createCol(prims, "GroupID", typeof(String)); + createCol(prims, "LastOwnerID", typeof(String)); + createCol(prims, "OwnerMask", typeof(Int32)); + createCol(prims, "NextOwnerMask", typeof(Int32)); + createCol(prims, "GroupMask", typeof(Int32)); + createCol(prims, "EveryoneMask", typeof(Int32)); + createCol(prims, "BaseMask", typeof(Int32)); + // vectors + createCol(prims, "PositionX", typeof(Double)); + createCol(prims, "PositionY", typeof(Double)); + createCol(prims, "PositionZ", typeof(Double)); + createCol(prims, "GroupPositionX", typeof(Double)); + createCol(prims, "GroupPositionY", typeof(Double)); + createCol(prims, "GroupPositionZ", typeof(Double)); + createCol(prims, "VelocityX", typeof(Double)); + createCol(prims, "VelocityY", typeof(Double)); + createCol(prims, "VelocityZ", typeof(Double)); + createCol(prims, "AngularVelocityX", typeof(Double)); + createCol(prims, "AngularVelocityY", typeof(Double)); + createCol(prims, "AngularVelocityZ", typeof(Double)); + createCol(prims, "AccelerationX", typeof(Double)); + createCol(prims, "AccelerationY", typeof(Double)); + createCol(prims, "AccelerationZ", typeof(Double)); + // quaternions + createCol(prims, "RotationX", typeof(Double)); + createCol(prims, "RotationY", typeof(Double)); + createCol(prims, "RotationZ", typeof(Double)); + createCol(prims, "RotationW", typeof(Double)); + + // sit target + createCol(prims, "SitTargetOffsetX", typeof(Double)); + createCol(prims, "SitTargetOffsetY", typeof(Double)); + createCol(prims, "SitTargetOffsetZ", typeof(Double)); + + createCol(prims, "SitTargetOrientW", typeof(Double)); + createCol(prims, "SitTargetOrientX", typeof(Double)); + createCol(prims, "SitTargetOrientY", typeof(Double)); + createCol(prims, "SitTargetOrientZ", typeof(Double)); + + // Add in contraints + prims.PrimaryKey = new DataColumn[] { prims.Columns["UUID"] }; + + return prims; + } + + private DataTable createLandTable() + { + DataTable land = new DataTable("land"); + createCol(land, "UUID", typeof(String)); + createCol(land, "RegionUUID", typeof(String)); + createCol(land, "LocalLandID", typeof(Int32)); + + // Bitmap is a byte[512] + createCol(land, "Bitmap", typeof(Byte[])); + + createCol(land, "Name", typeof(String)); + createCol(land, "Description", typeof(String)); + createCol(land, "OwnerUUID", typeof(String)); + createCol(land, "IsGroupOwned", typeof(Int32)); + createCol(land, "Area", typeof(Int32)); + createCol(land, "AuctionID", typeof(Int32)); //Unemplemented + createCol(land, "Category", typeof(Int32)); //Enum libsecondlife.Parcel.ParcelCategory + createCol(land, "ClaimDate", typeof(Int32)); + createCol(land, "ClaimPrice", typeof(Int32)); + createCol(land, "GroupUUID", typeof(String)); + createCol(land, "SalePrice", typeof(Int32)); + createCol(land, "LandStatus", typeof(Int32)); //Enum. libsecondlife.Parcel.ParcelStatus + createCol(land, "LandFlags", typeof(Int32)); + createCol(land, "LandingType", typeof(Int32)); + createCol(land, "MediaAutoScale", typeof(Int32)); + createCol(land, "MediaTextureUUID", typeof(String)); + createCol(land, "MediaURL", typeof(String)); + createCol(land, "MusicURL", typeof(String)); + createCol(land, "PassHours", typeof(Double)); + createCol(land, "PassPrice", typeof(Int32)); + createCol(land, "SnapshotUUID", typeof(String)); + createCol(land, "UserLocationX", typeof(Double)); + createCol(land, "UserLocationY", typeof(Double)); + createCol(land, "UserLocationZ", typeof(Double)); + createCol(land, "UserLookAtX", typeof(Double)); + createCol(land, "UserLookAtY", typeof(Double)); + createCol(land, "UserLookAtZ", typeof(Double)); + + land.PrimaryKey = new DataColumn[] { land.Columns["UUID"] }; + + return land; + } + + private DataTable createLandAccessListTable() + { + DataTable landaccess = new DataTable("landaccesslist"); + createCol(landaccess, "LandUUID", typeof(String)); + createCol(landaccess, "AccessUUID", typeof(String)); + createCol(landaccess, "Flags", typeof(Int32)); + + return landaccess; + } + + private DataTable createShapeTable() + { + DataTable shapes = new DataTable("primshapes"); + createCol(shapes, "UUID", typeof(String)); + // shape is an enum + createCol(shapes, "Shape", typeof(Int32)); + // vectors + createCol(shapes, "ScaleX", typeof(Double)); + createCol(shapes, "ScaleY", typeof(Double)); + createCol(shapes, "ScaleZ", typeof(Double)); + // paths + createCol(shapes, "PCode", typeof(Int32)); + createCol(shapes, "PathBegin", typeof(Int32)); + createCol(shapes, "PathEnd", typeof(Int32)); + createCol(shapes, "PathScaleX", typeof(Int32)); + createCol(shapes, "PathScaleY", typeof(Int32)); + createCol(shapes, "PathShearX", typeof(Int32)); + createCol(shapes, "PathShearY", typeof(Int32)); + createCol(shapes, "PathSkew", typeof(Int32)); + createCol(shapes, "PathCurve", typeof(Int32)); + createCol(shapes, "PathRadiusOffset", typeof(Int32)); + createCol(shapes, "PathRevolutions", typeof(Int32)); + createCol(shapes, "PathTaperX", typeof(Int32)); + createCol(shapes, "PathTaperY", typeof(Int32)); + createCol(shapes, "PathTwist", typeof(Int32)); + createCol(shapes, "PathTwistBegin", typeof(Int32)); + // profile + createCol(shapes, "ProfileBegin", typeof(Int32)); + createCol(shapes, "ProfileEnd", typeof(Int32)); + createCol(shapes, "ProfileCurve", typeof(Int32)); + createCol(shapes, "ProfileHollow", typeof(Int32)); + createCol(shapes, "State", typeof(Int32)); + // text TODO: this isn't right, but I'm not sure the right + // way to specify this as a blob atm + createCol(shapes, "Texture", typeof(Byte[])); + createCol(shapes, "ExtraParams", typeof(Byte[])); + + shapes.PrimaryKey = new DataColumn[] { shapes.Columns["UUID"] }; + + return shapes; + } + + private DataTable createItemsTable() + { + DataTable items = new DataTable("primitems"); + + createCol(items, "itemID", typeof(String)); + createCol(items, "primID", typeof(String)); + createCol(items, "assetID", typeof(String)); + createCol(items, "parentFolderID", typeof(String)); + + createCol(items, "invType", typeof(Int32)); + createCol(items, "assetType", typeof(Int32)); + + createCol(items, "name", typeof(String)); + createCol(items, "description", typeof(String)); + + createCol(items, "creationDate", typeof(Int64)); + createCol(items, "creatorID", typeof(String)); + createCol(items, "ownerID", typeof(String)); + createCol(items, "lastOwnerID", typeof(String)); + createCol(items, "groupID", typeof(String)); + + createCol(items, "nextPermissions", typeof(Int32)); + createCol(items, "currentPermissions", typeof(Int32)); + createCol(items, "basePermissions", typeof(Int32)); + createCol(items, "everyonePermissions", typeof(Int32)); + createCol(items, "groupPermissions", typeof(Int32)); + + items.PrimaryKey = new DataColumn[] { items.Columns["itemID"] }; + + return items; + } + + /*********************************************************************** + * + * Convert between ADO.NET <=> OpenSim Objects + * + * These should be database independant + * + **********************************************************************/ + + private SceneObjectPart buildPrim(DataRow row) + { + SceneObjectPart prim = new SceneObjectPart(); + prim.UUID = new LLUUID((String)row["UUID"]); + // explicit conversion of integers is required, which sort + // of sucks. No idea if there is a shortcut here or not. + prim.ParentID = Convert.ToUInt32(row["ParentID"]); + prim.CreationDate = Convert.ToInt32(row["CreationDate"]); + prim.Name = (String)row["Name"]; + // various text fields + prim.Text = (String)row["Text"]; + prim.Description = (String)row["Description"]; + prim.SitName = (String)row["SitName"]; + prim.TouchName = (String)row["TouchName"]; + // permissions + prim.ObjectFlags = Convert.ToUInt32(row["ObjectFlags"]); + prim.CreatorID = new LLUUID((String)row["CreatorID"]); + prim.OwnerID = new LLUUID((String)row["OwnerID"]); + prim.GroupID = new LLUUID((String)row["GroupID"]); + prim.LastOwnerID = new LLUUID((String)row["LastOwnerID"]); + prim.OwnerMask = Convert.ToUInt32(row["OwnerMask"]); + prim.NextOwnerMask = Convert.ToUInt32(row["NextOwnerMask"]); + prim.GroupMask = Convert.ToUInt32(row["GroupMask"]); + prim.EveryoneMask = Convert.ToUInt32(row["EveryoneMask"]); + prim.BaseMask = Convert.ToUInt32(row["BaseMask"]); + // vectors + prim.OffsetPosition = new LLVector3( + Convert.ToSingle(row["PositionX"]), + Convert.ToSingle(row["PositionY"]), + Convert.ToSingle(row["PositionZ"]) + ); + prim.GroupPosition = new LLVector3( + Convert.ToSingle(row["GroupPositionX"]), + Convert.ToSingle(row["GroupPositionY"]), + Convert.ToSingle(row["GroupPositionZ"]) + ); + prim.Velocity = new LLVector3( + Convert.ToSingle(row["VelocityX"]), + Convert.ToSingle(row["VelocityY"]), + Convert.ToSingle(row["VelocityZ"]) + ); + prim.AngularVelocity = new LLVector3( + Convert.ToSingle(row["AngularVelocityX"]), + Convert.ToSingle(row["AngularVelocityY"]), + Convert.ToSingle(row["AngularVelocityZ"]) + ); + prim.Acceleration = new LLVector3( + Convert.ToSingle(row["AccelerationX"]), + Convert.ToSingle(row["AccelerationY"]), + Convert.ToSingle(row["AccelerationZ"]) + ); + // quaternions + prim.RotationOffset = new LLQuaternion( + Convert.ToSingle(row["RotationX"]), + Convert.ToSingle(row["RotationY"]), + Convert.ToSingle(row["RotationZ"]), + Convert.ToSingle(row["RotationW"]) + ); + try + { + prim.SetSitTargetLL(new LLVector3( + Convert.ToSingle(row["SitTargetOffsetX"]), + Convert.ToSingle(row["SitTargetOffsetY"]), + Convert.ToSingle(row["SitTargetOffsetZ"])), new LLQuaternion( + Convert.ToSingle( + row["SitTargetOrientX"]), + Convert.ToSingle( + row["SitTargetOrientY"]), + Convert.ToSingle( + row["SitTargetOrientZ"]), + Convert.ToSingle( + row["SitTargetOrientW"]))); + } + catch (InvalidCastException) + { + // Database table was created before we got here and now has null values :P + + using ( + SqlCommand cmd = + new SqlCommand( + "ALTER TABLE [prims] ADD COLUMN [SitTargetOffsetX] float NOT NULL default 0, ADD COLUMN [SitTargetOffsetY] float NOT NULL default 0, ADD COLUMN [SitTargetOffsetZ] float NOT NULL default 0, ADD COLUMN [SitTargetOrientW] float NOT NULL default 0, ADD COLUMN [SitTargetOrientX] float NOT NULL default 0, ADD COLUMN [SitTargetOrientY] float NOT NULL default 0, ADD COLUMN [SitTargetOrientZ] float NOT NULL default 0;", + m_connection)) + { + cmd.ExecuteNonQuery(); + } + } + + return prim; + } + + /// + /// Build a prim inventory item from the persisted data. + /// + /// + /// + private TaskInventoryItem buildItem(DataRow row) + { + TaskInventoryItem taskItem = new TaskInventoryItem(); + + taskItem.ItemID = new LLUUID((String)row["itemID"]); + taskItem.ParentPartID = new LLUUID((String)row["primID"]); + taskItem.AssetID = new LLUUID((String)row["assetID"]); + taskItem.ParentID = new LLUUID((String)row["parentFolderID"]); + + taskItem.InvType = Convert.ToInt32(row["invType"]); + taskItem.Type = Convert.ToInt32(row["assetType"]); + + taskItem.Name = (String)row["name"]; + taskItem.Description = (String)row["description"]; + taskItem.CreationDate = Convert.ToUInt32(row["creationDate"]); + taskItem.CreatorID = new LLUUID((String)row["creatorID"]); + taskItem.OwnerID = new LLUUID((String)row["ownerID"]); + taskItem.LastOwnerID = new LLUUID((String)row["lastOwnerID"]); + taskItem.GroupID = new LLUUID((String)row["groupID"]); + + taskItem.NextOwnerMask = Convert.ToUInt32(row["nextPermissions"]); + taskItem.OwnerMask = Convert.ToUInt32(row["currentPermissions"]); + taskItem.BaseMask = Convert.ToUInt32(row["basePermissions"]); + taskItem.EveryoneMask = Convert.ToUInt32(row["everyonePermissions"]); + taskItem.GroupMask = Convert.ToUInt32(row["groupPermissions"]); + + return taskItem; + } + + private LandData buildLandData(DataRow row) + { + LandData newData = new LandData(); + + newData.globalID = new LLUUID((String)row["UUID"]); + newData.localID = Convert.ToInt32(row["LocalLandID"]); + + // Bitmap is a byte[512] + newData.landBitmapByteArray = (Byte[])row["Bitmap"]; + + newData.landName = (String)row["Name"]; + newData.landDesc = (String)row["Description"]; + newData.ownerID = (String)row["OwnerUUID"]; + newData.isGroupOwned = Convert.ToBoolean(row["IsGroupOwned"]); + newData.area = Convert.ToInt32(row["Area"]); + newData.auctionID = Convert.ToUInt32(row["AuctionID"]); //Unemplemented + newData.category = (Parcel.ParcelCategory)Convert.ToInt32(row["Category"]); + //Enum libsecondlife.Parcel.ParcelCategory + newData.claimDate = Convert.ToInt32(row["ClaimDate"]); + newData.claimPrice = Convert.ToInt32(row["ClaimPrice"]); + newData.groupID = new LLUUID((String)row["GroupUUID"]); + newData.salePrice = Convert.ToInt32(row["SalePrice"]); + newData.landStatus = (Parcel.ParcelStatus)Convert.ToInt32(row["LandStatus"]); + //Enum. libsecondlife.Parcel.ParcelStatus + newData.landFlags = Convert.ToUInt32(row["LandFlags"]); + newData.landingType = Convert.ToByte(row["LandingType"]); + newData.mediaAutoScale = Convert.ToByte(row["MediaAutoScale"]); + newData.mediaID = new LLUUID((String)row["MediaTextureUUID"]); + newData.mediaURL = (String)row["MediaURL"]; + newData.musicURL = (String)row["MusicURL"]; + newData.passHours = Convert.ToSingle(row["PassHours"]); + newData.passPrice = Convert.ToInt32(row["PassPrice"]); + newData.snapshotID = (String)row["SnapshotUUID"]; + + newData.userLocation = + new LLVector3(Convert.ToSingle(row["UserLocationX"]), Convert.ToSingle(row["UserLocationY"]), + Convert.ToSingle(row["UserLocationZ"])); + newData.userLookAt = + new LLVector3(Convert.ToSingle(row["UserLookAtX"]), Convert.ToSingle(row["UserLookAtY"]), + Convert.ToSingle(row["UserLookAtZ"])); + newData.parcelAccessList = new List(); + + return newData; + } + + private ParcelManager.ParcelAccessEntry buildLandAccessData(DataRow row) + { + ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry(); + entry.AgentID = new LLUUID((string)row["AccessUUID"]); + entry.Flags = (ParcelManager.AccessList)Convert.ToInt32(row["Flags"]); + entry.Time = new DateTime(); + return entry; + } + + private Array serializeTerrain(double[,] val) + { + MemoryStream str = new MemoryStream(65536 * sizeof(double)); + BinaryWriter bw = new BinaryWriter(str); + + // TODO: COMPATIBILITY - Add byte-order conversions + for (int x = 0; x < 256; x++) + for (int y = 0; y < 256; y++) + bw.Write(val[x, y]); + + return str.ToArray(); + } + + private void fillPrimRow(DataRow row, SceneObjectPart prim, LLUUID sceneGroupID, LLUUID regionUUID) + { + row["UUID"] = prim.UUID; + row["RegionUUID"] = regionUUID; + row["ParentID"] = prim.ParentID; + row["CreationDate"] = prim.CreationDate; + row["Name"] = prim.Name; + row["SceneGroupID"] = sceneGroupID; + // the UUID of the root part for this SceneObjectGroup + // various text fields + row["Text"] = prim.Text; + row["Description"] = prim.Description; + row["SitName"] = prim.SitName; + row["TouchName"] = prim.TouchName; + // permissions + row["ObjectFlags"] = prim.ObjectFlags; + row["CreatorID"] = prim.CreatorID; + row["OwnerID"] = prim.OwnerID; + row["GroupID"] = prim.GroupID; + row["LastOwnerID"] = prim.LastOwnerID; + row["OwnerMask"] = prim.OwnerMask; + row["NextOwnerMask"] = prim.NextOwnerMask; + row["GroupMask"] = prim.GroupMask; + row["EveryoneMask"] = prim.EveryoneMask; + row["BaseMask"] = prim.BaseMask; + // vectors + row["PositionX"] = prim.OffsetPosition.X; + row["PositionY"] = prim.OffsetPosition.Y; + row["PositionZ"] = prim.OffsetPosition.Z; + row["GroupPositionX"] = prim.GroupPosition.X; + row["GroupPositionY"] = prim.GroupPosition.Y; + row["GroupPositionZ"] = prim.GroupPosition.Z; + row["VelocityX"] = prim.Velocity.X; + row["VelocityY"] = prim.Velocity.Y; + row["VelocityZ"] = prim.Velocity.Z; + row["AngularVelocityX"] = prim.AngularVelocity.X; + row["AngularVelocityY"] = prim.AngularVelocity.Y; + row["AngularVelocityZ"] = prim.AngularVelocity.Z; + row["AccelerationX"] = prim.Acceleration.X; + row["AccelerationY"] = prim.Acceleration.Y; + row["AccelerationZ"] = prim.Acceleration.Z; + // quaternions + row["RotationX"] = prim.RotationOffset.X; + row["RotationY"] = prim.RotationOffset.Y; + row["RotationZ"] = prim.RotationOffset.Z; + row["RotationW"] = prim.RotationOffset.W; + + try + { + // Sit target + LLVector3 sitTargetPos = prim.GetSitTargetPositionLL(); + row["SitTargetOffsetX"] = sitTargetPos.X; + row["SitTargetOffsetY"] = sitTargetPos.Y; + row["SitTargetOffsetZ"] = sitTargetPos.Z; + + LLQuaternion sitTargetOrient = prim.GetSitTargetOrientationLL(); + row["SitTargetOrientW"] = sitTargetOrient.W; + row["SitTargetOrientX"] = sitTargetOrient.X; + row["SitTargetOrientY"] = sitTargetOrient.Y; + row["SitTargetOrientZ"] = sitTargetOrient.Z; + } + catch (Exception) + { + // Database table was created before we got here and needs to be created! :P + + using ( + SqlCommand cmd = + new SqlCommand( + "ALTER TABLE [prims] ADD COLUMN [SitTargetOffsetX] float NOT NULL default 0, ADD COLUMN [SitTargetOffsetY] float NOT NULL default 0, ADD COLUMN [SitTargetOffsetZ] float NOT NULL default 0, ADD COLUMN [SitTargetOrientW] float NOT NULL default 0, ADD COLUMN [SitTargetOrientX] float NOT NULL default 0, ADD COLUMN [SitTargetOrientY] float NOT NULL default 0, ADD COLUMN [SitTargetOrientZ] float NOT NULL default 0;", + m_connection)) + { + cmd.ExecuteNonQuery(); + } + } + } + + private void fillItemRow(DataRow row, TaskInventoryItem taskItem) + { + row["itemID"] = taskItem.ItemID; + row["primID"] = taskItem.ParentPartID; + row["assetID"] = taskItem.AssetID; + row["parentFolderID"] = taskItem.ParentID; + + row["invType"] = taskItem.InvType; + row["assetType"] = taskItem.Type; + + row["name"] = taskItem.Name; + row["description"] = taskItem.Description; + row["creationDate"] = taskItem.CreationDate; + row["creatorID"] = taskItem.CreatorID; + row["ownerID"] = taskItem.OwnerID; + row["lastOwnerID"] = taskItem.LastOwnerID; + row["groupID"] = taskItem.GroupID; + row["nextPermissions"] = taskItem.NextOwnerMask; + row["currentPermissions"] = taskItem.OwnerMask; + row["basePermissions"] = taskItem.BaseMask; + row["everyonePermissions"] = taskItem.EveryoneMask; + row["groupPermissions"] = taskItem.GroupMask; + } + + private void fillLandRow(DataRow row, LandData land, LLUUID regionUUID) + { + row["UUID"] = land.globalID.UUID; + row["RegionUUID"] = regionUUID.UUID; + row["LocalLandID"] = land.localID; + + // Bitmap is a byte[512] + row["Bitmap"] = land.landBitmapByteArray; + + row["Name"] = land.landName; + row["Description"] = land.landDesc; + row["OwnerUUID"] = land.ownerID.UUID; + row["IsGroupOwned"] = land.isGroupOwned; + row["Area"] = land.area; + row["AuctionID"] = land.auctionID; //Unemplemented + row["Category"] = land.category; //Enum libsecondlife.Parcel.ParcelCategory + row["ClaimDate"] = land.claimDate; + row["ClaimPrice"] = land.claimPrice; + row["GroupUUID"] = land.groupID.UUID; + row["SalePrice"] = land.salePrice; + row["LandStatus"] = land.landStatus; //Enum. libsecondlife.Parcel.ParcelStatus + row["LandFlags"] = land.landFlags; + row["LandingType"] = land.landingType; + row["MediaAutoScale"] = land.mediaAutoScale; + row["MediaTextureUUID"] = land.mediaID.UUID; + row["MediaURL"] = land.mediaURL; + row["MusicURL"] = land.musicURL; + row["PassHours"] = land.passHours; + row["PassPrice"] = land.passPrice; + row["SnapshotUUID"] = land.snapshotID.UUID; + row["UserLocationX"] = land.userLocation.X; + row["UserLocationY"] = land.userLocation.Y; + row["UserLocationZ"] = land.userLocation.Z; + row["UserLookAtX"] = land.userLookAt.X; + row["UserLookAtY"] = land.userLookAt.Y; + row["UserLookAtZ"] = land.userLookAt.Z; + } + + private void fillLandAccessRow(DataRow row, ParcelManager.ParcelAccessEntry entry, LLUUID parcelID) + { + row["LandUUID"] = parcelID.UUID; + row["AccessUUID"] = entry.AgentID.UUID; + row["Flags"] = entry.Flags; + } + + private PrimitiveBaseShape buildShape(DataRow row) + { + PrimitiveBaseShape s = new PrimitiveBaseShape(); + s.Scale = new LLVector3( + Convert.ToSingle(row["ScaleX"]), + Convert.ToSingle(row["ScaleY"]), + Convert.ToSingle(row["ScaleZ"]) + ); + // paths + s.PCode = Convert.ToByte(row["PCode"]); + s.PathBegin = Convert.ToUInt16(row["PathBegin"]); + s.PathEnd = Convert.ToUInt16(row["PathEnd"]); + s.PathScaleX = Convert.ToByte(row["PathScaleX"]); + s.PathScaleY = Convert.ToByte(row["PathScaleY"]); + s.PathShearX = Convert.ToByte(row["PathShearX"]); + s.PathShearY = Convert.ToByte(row["PathShearY"]); + s.PathSkew = Convert.ToSByte(row["PathSkew"]); + s.PathCurve = Convert.ToByte(row["PathCurve"]); + s.PathRadiusOffset = Convert.ToSByte(row["PathRadiusOffset"]); + s.PathRevolutions = Convert.ToByte(row["PathRevolutions"]); + s.PathTaperX = Convert.ToSByte(row["PathTaperX"]); + s.PathTaperY = Convert.ToSByte(row["PathTaperY"]); + s.PathTwist = Convert.ToSByte(row["PathTwist"]); + s.PathTwistBegin = Convert.ToSByte(row["PathTwistBegin"]); + // profile + s.ProfileBegin = Convert.ToUInt16(row["ProfileBegin"]); + s.ProfileEnd = Convert.ToUInt16(row["ProfileEnd"]); + s.ProfileCurve = Convert.ToByte(row["ProfileCurve"]); + s.ProfileHollow = Convert.ToUInt16(row["ProfileHollow"]); + s.State = Convert.ToByte(row["State"]); + + byte[] textureEntry = (byte[])row["Texture"]; + s.TextureEntry = textureEntry; + + s.ExtraParams = (byte[])row["ExtraParams"]; + + return s; + } + + private void fillShapeRow(DataRow row, SceneObjectPart prim) + { + PrimitiveBaseShape s = prim.Shape; + row["UUID"] = prim.UUID; + // shape is an enum + row["Shape"] = 0; + // vectors + row["ScaleX"] = s.Scale.X; + row["ScaleY"] = s.Scale.Y; + row["ScaleZ"] = s.Scale.Z; + // paths + row["PCode"] = s.PCode; + row["PathBegin"] = s.PathBegin; + row["PathEnd"] = s.PathEnd; + row["PathScaleX"] = s.PathScaleX; + row["PathScaleY"] = s.PathScaleY; + row["PathShearX"] = s.PathShearX; + row["PathShearY"] = s.PathShearY; + row["PathSkew"] = s.PathSkew; + row["PathCurve"] = s.PathCurve; + row["PathRadiusOffset"] = s.PathRadiusOffset; + row["PathRevolutions"] = s.PathRevolutions; + row["PathTaperX"] = s.PathTaperX; + row["PathTaperY"] = s.PathTaperY; + row["PathTwist"] = s.PathTwist; + row["PathTwistBegin"] = s.PathTwistBegin; + // profile + row["ProfileBegin"] = s.ProfileBegin; + row["ProfileEnd"] = s.ProfileEnd; + row["ProfileCurve"] = s.ProfileCurve; + row["ProfileHollow"] = s.ProfileHollow; + row["State"] = s.State; + row["Texture"] = s.TextureEntry; + row["ExtraParams"] = s.ExtraParams; + } + + private void addPrim(SceneObjectPart prim, LLUUID sceneGroupID, LLUUID regionUUID) + { + DataTable prims = m_dataSet.Tables["prims"]; + DataTable shapes = m_dataSet.Tables["primshapes"]; + + DataRow primRow = prims.Rows.Find(prim.UUID); + if (primRow == null) + { + primRow = prims.NewRow(); + fillPrimRow(primRow, prim, sceneGroupID, regionUUID); + prims.Rows.Add(primRow); + } + else + { + fillPrimRow(primRow, prim, sceneGroupID, regionUUID); + } + + DataRow shapeRow = shapes.Rows.Find(prim.UUID); + if (shapeRow == null) + { + shapeRow = shapes.NewRow(); + fillShapeRow(shapeRow, prim); + shapes.Rows.Add(shapeRow); + } + else + { + fillShapeRow(shapeRow, prim); + } + } + + // see IRegionDatastore + public void StorePrimInventory(LLUUID primID, ICollection items) + { + if (!persistPrimInventories) + return; + + m_log.InfoFormat("[DATASTORE]: Persisting Prim Inventory with prim ID {0}", primID); + + // For now, we're just going to crudely remove all the previous inventory items + // no matter whether they have changed or not, and replace them with the current set. + lock (m_dataSet) + { + RemoveItems(primID); + + // repalce with current inventory details + foreach (TaskInventoryItem newItem in items) + { + // m_log.InfoFormat( + // "[DATASTORE]: " + + // "Adding item {0}, {1} to prim ID {2}", + // newItem.Name, newItem.ItemID, newItem.ParentPartID); + + DataRow newItemRow = m_itemsTable.NewRow(); + fillItemRow(newItemRow, newItem); + m_itemsTable.Rows.Add(newItemRow); + } + } + + Commit(); + } + + /*********************************************************************** + * + * SQL Statement Creation Functions + * + * These functions create SQL statements for update, insert, and create. + * They can probably be factored later to have a db independant + * portion and a db specific portion + * + **********************************************************************/ + + private SqlCommand createInsertCommand(string table, DataTable dt) + { + /** + * This is subtle enough to deserve some commentary. + * Instead of doing *lots* and *lots of hardcoded strings + * for database definitions we'll use the fact that + * realistically all insert statements look like "insert + * into A(b, c) values(:b, :c) on the parameterized query + * front. If we just have a list of b, c, etc... we can + * generate these strings instead of typing them out. + */ + string[] cols = new string[dt.Columns.Count]; + for (int i = 0; i < dt.Columns.Count; i++) + { + DataColumn col = dt.Columns[i]; + cols[i] = col.ColumnName; + } + + string sql = "insert into " + table + "("; + sql += String.Join(", ", cols); + // important, the first ':' needs to be here, the rest get added in the join + sql += ") values (@"; + sql += String.Join(", @", cols); + sql += ")"; + SqlCommand cmd = new SqlCommand(sql); + + // this provides the binding for all our parameters, so + // much less code than it used to be + foreach (DataColumn col in dt.Columns) + { + cmd.Parameters.Add(createSqlParameter(col.ColumnName, col.DataType)); + } + return cmd; + } + + private SqlCommand createUpdateCommand(string table, string pk, DataTable dt) + { + string sql = "update " + table + " set "; + string subsql = String.Empty; + foreach (DataColumn col in dt.Columns) + { + if (subsql.Length > 0) + { + // a map function would rock so much here + subsql += ", "; + } + subsql += col.ColumnName + "= @" + col.ColumnName; + } + sql += subsql; + sql += " where " + pk; + SqlCommand cmd = new SqlCommand(sql); + + // this provides the binding for all our parameters, so + // much less code than it used to be + + foreach (DataColumn col in dt.Columns) + { + cmd.Parameters.Add(createSqlParameter(col.ColumnName, col.DataType)); + } + return cmd; + } + + private string defineTable(DataTable dt) + { + string sql = "create table " + dt.TableName + "("; + string subsql = String.Empty; + foreach (DataColumn col in dt.Columns) + { + if (subsql.Length > 0) + { + // a map function would rock so much here + subsql += ",\n"; + } + subsql += col.ColumnName + " " + MSSQLManager.SqlType(col.DataType); + if (dt.PrimaryKey.Length > 0 && col == dt.PrimaryKey[0]) + { + subsql += " primary key"; + } + } + sql += subsql; + sql += ")"; + + return sql; + } + + /*********************************************************************** + * + * Database Binding functions + * + * These will be db specific due to typing, and minor differences + * in databases. + * + **********************************************************************/ + + /// + /// This is a convenience function that collapses 5 repetitive + /// lines for defining SqlParameters to 2 parameters: + /// column name and database type. + /// + /// It assumes certain conventions like :param as the param + /// name to replace in parametrized queries, and that source + /// version is always current version, both of which are fine + /// for us. + /// + ///a built Sql parameter + private SqlParameter createSqlParameter(string name, Type type) + { + SqlParameter param = new SqlParameter(); + param.ParameterName = "@" + name; + param.DbType = dbtypeFromType(type); + param.SourceColumn = name; + param.SourceVersion = DataRowVersion.Current; + return param; + } + +// TODO: unused +// private SqlParameter createParamWithValue(string name, Type type, Object o) +// { +// SqlParameter param = createSqlParameter(name, type); +// param.Value = o; +// return param; +// } + + private void setupPrimCommands(SqlDataAdapter da, SqlConnection conn) + { + da.InsertCommand = createInsertCommand("prims", m_dataSet.Tables["prims"]); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("prims", "UUID=@UUID", m_dataSet.Tables["prims"]); + da.UpdateCommand.Connection = conn; + + SqlCommand delete = new SqlCommand("delete from prims where UUID = @UUID"); + delete.Parameters.Add(createSqlParameter("UUID", typeof(String))); + delete.Connection = conn; + da.DeleteCommand = delete; + } + + private void SetupItemsCommands(SqlDataAdapter da, SqlConnection conn) + { + da.InsertCommand = createInsertCommand("primitems", m_itemsTable); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("primitems", "itemID = @itemID", m_itemsTable); + da.UpdateCommand.Connection = conn; + + SqlCommand delete = new SqlCommand("delete from primitems where itemID = @itemID"); + delete.Parameters.Add(createSqlParameter("itemID", typeof(String))); + delete.Connection = conn; + da.DeleteCommand = delete; + } + + private void setupTerrainCommands(SqlDataAdapter da, SqlConnection conn) + { + da.InsertCommand = createInsertCommand("terrain", m_dataSet.Tables["terrain"]); + da.InsertCommand.Connection = conn; + } + + private void setupLandCommands(SqlDataAdapter da, SqlConnection conn) + { + da.InsertCommand = createInsertCommand("land", m_dataSet.Tables["land"]); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("land", "UUID=@UUID", m_dataSet.Tables["land"]); + da.UpdateCommand.Connection = conn; + } + + private void setupLandAccessCommands(SqlDataAdapter da, SqlConnection conn) + { + da.InsertCommand = createInsertCommand("landaccesslist", m_dataSet.Tables["landaccesslist"]); + da.InsertCommand.Connection = conn; + } + + private void setupShapeCommands(SqlDataAdapter da, SqlConnection conn) + { + da.InsertCommand = createInsertCommand("primshapes", m_dataSet.Tables["primshapes"]); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("primshapes", "UUID=@UUID", m_dataSet.Tables["primshapes"]); + da.UpdateCommand.Connection = conn; + + SqlCommand delete = new SqlCommand("delete from primshapes where UUID = @UUID"); + delete.Parameters.Add(createSqlParameter("UUID", typeof(String))); + delete.Connection = conn; + da.DeleteCommand = delete; + } + + private void InitDB(SqlConnection conn) + { + string createPrims = defineTable(createPrimTable()); + string createShapes = defineTable(createShapeTable()); + string createItems = defineTable(createItemsTable()); + string createTerrain = defineTable(createTerrainTable()); + string createLand = defineTable(createLandTable()); + string createLandAccessList = defineTable(createLandAccessListTable()); + + SqlCommand pcmd = new SqlCommand(createPrims, conn); + SqlCommand scmd = new SqlCommand(createShapes, conn); + SqlCommand icmd = new SqlCommand(createItems, conn); + SqlCommand tcmd = new SqlCommand(createTerrain, conn); + SqlCommand lcmd = new SqlCommand(createLand, conn); + SqlCommand lalcmd = new SqlCommand(createLandAccessList, conn); + + conn.Open(); + try + { + pcmd.ExecuteNonQuery(); + } + catch (SqlException e) + { + m_log.WarnFormat("[MSSql]: Primitives Table Already Exists: {0}", e); + } + + try + { + scmd.ExecuteNonQuery(); + } + catch (SqlException e) + { + m_log.WarnFormat("[MSSql]: Shapes Table Already Exists: {0}", e); + } + + try + { + icmd.ExecuteNonQuery(); + } + catch (SqlException e) + { + m_log.WarnFormat("[MSSql]: Items Table Already Exists: {0}", e); + } + + try + { + tcmd.ExecuteNonQuery(); + } + catch (SqlException e) + { + m_log.WarnFormat("[MSSql]: Terrain Table Already Exists: {0}", e); + } + + try + { + lcmd.ExecuteNonQuery(); + } + catch (SqlException e) + { + m_log.WarnFormat("[MSSql]: Land Table Already Exists: {0}", e); + } + + try + { + lalcmd.ExecuteNonQuery(); + } + catch (SqlException e) + { + m_log.WarnFormat("[MSSql]: LandAccessList Table Already Exists: {0}", e); + } + conn.Close(); + } + + private bool TestTables(SqlConnection conn) + { + SqlCommand primSelectCmd = new SqlCommand(m_primSelect, conn); + SqlDataAdapter pDa = new SqlDataAdapter(primSelectCmd); + SqlCommand shapeSelectCmd = new SqlCommand(m_shapeSelect, conn); + SqlDataAdapter sDa = new SqlDataAdapter(shapeSelectCmd); + SqlCommand itemsSelectCmd = new SqlCommand(m_itemsSelect, conn); + SqlDataAdapter iDa = new SqlDataAdapter(itemsSelectCmd); + SqlCommand terrainSelectCmd = new SqlCommand(m_terrainSelect, conn); + SqlDataAdapter tDa = new SqlDataAdapter(terrainSelectCmd); + SqlCommand landSelectCmd = new SqlCommand(m_landSelect, conn); + SqlDataAdapter lDa = new SqlDataAdapter(landSelectCmd); + SqlCommand landAccessListSelectCmd = new SqlCommand(m_landAccessListSelect, conn); + SqlDataAdapter lalDa = new SqlDataAdapter(landAccessListSelectCmd); + + DataSet tmpDS = new DataSet(); + try + { + pDa.Fill(tmpDS, "prims"); + sDa.Fill(tmpDS, "primshapes"); + + if (persistPrimInventories) + iDa.Fill(tmpDS, "primitems"); + + tDa.Fill(tmpDS, "terrain"); + lDa.Fill(tmpDS, "land"); + lalDa.Fill(tmpDS, "landaccesslist"); + } + catch (SqlException) + { + m_log.Info("[DATASTORE]: MySql Database doesn't exist... creating"); + InitDB(conn); + } + + pDa.Fill(tmpDS, "prims"); + sDa.Fill(tmpDS, "primshapes"); + + if (persistPrimInventories) + iDa.Fill(tmpDS, "primitems"); + + tDa.Fill(tmpDS, "terrain"); + lDa.Fill(tmpDS, "land"); + lalDa.Fill(tmpDS, "landaccesslist"); + + foreach (DataColumn col in createPrimTable().Columns) + { + if (!tmpDS.Tables["prims"].Columns.Contains(col.ColumnName)) + { + m_log.Info("[DATASTORE]: Missing required column:" + col.ColumnName); + return false; + } + } + + foreach (DataColumn col in createShapeTable().Columns) + { + if (!tmpDS.Tables["primshapes"].Columns.Contains(col.ColumnName)) + { + m_log.Info("[DATASTORE]: Missing required column:" + col.ColumnName); + return false; + } + } + + // XXX primitems should probably go here eventually + + foreach (DataColumn col in createTerrainTable().Columns) + { + if (!tmpDS.Tables["terrain"].Columns.Contains(col.ColumnName)) + { + m_log.Info("[DATASTORE]: Missing require column:" + col.ColumnName); + return false; + } + } + + foreach (DataColumn col in createLandTable().Columns) + { + if (!tmpDS.Tables["land"].Columns.Contains(col.ColumnName)) + { + m_log.Info("[DATASTORE]: Missing require column:" + col.ColumnName); + return false; + } + } + + foreach (DataColumn col in createLandAccessListTable().Columns) + { + if (!tmpDS.Tables["landaccesslist"].Columns.Contains(col.ColumnName)) + { + m_log.Info("[DATASTORE]: Missing require column:" + col.ColumnName); + return false; + } + } + + return true; + } + + /*********************************************************************** + * + * Type conversion functions + * + **********************************************************************/ + + private DbType dbtypeFromType(Type type) + { + if (type == typeof(String)) + { + return DbType.String; + } + else if (type == typeof(Int32)) + { + return DbType.Int32; + } + else if (type == typeof(Double)) + { + return DbType.Double; + } + else if (type == typeof(Byte[])) + { + return DbType.Binary; + } + else + { + return DbType.String; + } + } + } +} diff --git a/OpenSim/Data/MSSQL/MSSQLGridData.cs b/OpenSim/Data/MSSQL/MSSQLGridData.cs new file mode 100644 index 0000000..9bd8acc --- /dev/null +++ b/OpenSim/Data/MSSQL/MSSQLGridData.cs @@ -0,0 +1,366 @@ +/* + * 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.Data; +using System.Security.Cryptography; +using System.Text; +using libsecondlife; +using OpenSim.Framework.Console; + +namespace OpenSim.Framework.Data.MSSQL +{ + /// + /// A grid data interface for Microsoft SQL Server + /// + public class MSSQLGridData : GridDataBase + { + private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// Database manager + /// + private MSSQLManager database; + + private string m_regionsTableName; + + /// + /// Initialises the Grid Interface + /// + override public void Initialise() + { + IniFile iniFile = new IniFile("mssql_connection.ini"); + + string settingDataSource = iniFile.ParseFileReadValue("data_source"); + string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog"); + string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info"); + string settingUserId = iniFile.ParseFileReadValue("user_id"); + string settingPassword = iniFile.ParseFileReadValue("password"); + + m_regionsTableName = iniFile.ParseFileReadValue("regionstablename"); + if (m_regionsTableName == null) + { + m_regionsTableName = "regions"; + } + + database = + new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, + settingPassword); + + TestTables(); + } + + private void TestTables() + { + IDbCommand cmd = database.Query("SELECT TOP 1 * FROM "+m_regionsTableName, new Dictionary()); + + try + { + cmd.ExecuteNonQuery(); + cmd.Dispose(); + } + catch (Exception) + { + m_log.Info("[DATASTORE]: MSSQL Database doesn't exist... creating"); + database.ExecuteResourceSql("Mssql-regions.sql"); + } + } + + /// + /// Shuts down the grid interface + /// + override public void Close() + { + database.Close(); + } + + /// + /// Returns the storage system name + /// + /// A string containing the storage system name + override public string getName() + { + return "Sql OpenGridData"; + } + + /// + /// Returns the storage system version + /// + /// A string containing the storage system version + override public string getVersion() + { + return "0.1"; + } + + /// + /// Returns a list of regions within the specified ranges + /// + /// minimum X coordinate + /// minimum Y coordinate + /// maximum X coordinate + /// maximum Y coordinate + /// An array of region profiles + override public RegionProfileData[] GetProfilesInRange(uint a, uint b, uint c, uint d) + { + return null; + } + + /// + /// Returns a sim profile from its location + /// + /// Region location handle + /// Sim profile + override public RegionProfileData GetProfileByHandle(ulong handle) + { + IDataReader reader = null; + try + { + Dictionary param = new Dictionary(); + param["handle"] = handle.ToString(); + IDbCommand result = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE regionHandle = @handle", param); + reader = result.ExecuteReader(); + + RegionProfileData row = database.getRegionRow(reader); + reader.Close(); + result.Dispose(); + + return row; + } + catch (Exception) + { + if (reader != null) + { + reader.Close(); + } + } + return null; + } + + /// + /// Returns a sim profile from its UUID + /// + /// The region UUID + /// The sim profile + override public RegionProfileData GetProfileByLLUUID(LLUUID uuid) + { + Dictionary param = new Dictionary(); + 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); + reader.Close(); + result.Dispose(); + + return row; + } + + /// + /// Returns a sim profile from it's Region name string + /// + /// The region name search query + /// The sim profile + override public RegionProfileData GetProfileByString(string regionName) + { + if (regionName.Length > 2) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + // Add % because this is a like query. + param["?regionName"] = regionName + "%"; + // 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); + IDataReader reader = result.ExecuteReader(); + + RegionProfileData row = database.getRegionRow(reader); + reader.Close(); + result.Dispose(); + + return row; + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return null; + } + } + else + { + m_log.Error("[DATABASE]: Searched for a Region Name shorter then 3 characters"); + return null; + } + } + + /// + /// Adds a new specified region to the database + /// + /// The profile to add + /// A dataresponse enum indicating success + override public DataResponse AddProfile(RegionProfileData profile) + { + try + { + if (GetProfileByLLUUID(profile.UUID) != null) + { + return DataResponse.RESPONSE_OK; + } + } + catch (Exception) + { + System.Console.WriteLine("No regions found. Create new one."); + } + + if (insertRegionRow(profile)) + { + return DataResponse.RESPONSE_OK; + } + else + { + return DataResponse.RESPONSE_ERROR; + } + } + + /// + /// Creates a new region in the database + /// + /// The region profile to insert + /// Successful? + public bool insertRegionRow(RegionProfileData profile) + { + //Insert new region + string sql = + "INSERT INTO " + m_regionsTableName + " ([regionHandle], [regionName], [uuid], [regionRecvKey], [regionSecret], [regionSendKey], [regionDataURI], "; + sql += + "[serverIP], [serverPort], [serverURI], [locX], [locY], [locZ], [eastOverrideHandle], [westOverrideHandle], [southOverrideHandle], [northOverrideHandle], [regionAssetURI], [regionAssetRecvKey], "; + sql += + "[regionAssetSendKey], [regionUserURI], [regionUserRecvKey], [regionUserSendKey], [regionMapTexture], [serverHttpPort], [serverRemotingPort], [owner_uuid]) VALUES "; + + sql += "(@regionHandle, @regionName, @uuid, @regionRecvKey, @regionSecret, @regionSendKey, @regionDataURI, "; + sql += + "@serverIP, @serverPort, @serverURI, @locX, @locY, @locZ, @eastOverrideHandle, @westOverrideHandle, @southOverrideHandle, @northOverrideHandle, @regionAssetURI, @regionAssetRecvKey, "; + sql += + "@regionAssetSendKey, @regionUserURI, @regionUserRecvKey, @regionUserSendKey, @regionMapTexture, @serverHttpPort, @serverRemotingPort, @owner_uuid);"; + + Dictionary parameters = new Dictionary(); + + parameters["regionHandle"] = profile.regionHandle.ToString(); + parameters["regionName"] = profile.regionName; + parameters["uuid"] = profile.UUID.ToString(); + parameters["regionRecvKey"] = profile.regionRecvKey; + parameters["regionSecret"] = profile.regionSecret; + parameters["regionSendKey"] = profile.regionSendKey; + parameters["regionDataURI"] = profile.regionDataURI; + parameters["serverIP"] = profile.serverIP; + parameters["serverPort"] = profile.serverPort.ToString(); + parameters["serverURI"] = profile.serverURI; + parameters["locX"] = profile.regionLocX.ToString(); + parameters["locY"] = profile.regionLocY.ToString(); + parameters["locZ"] = profile.regionLocZ.ToString(); + parameters["eastOverrideHandle"] = profile.regionEastOverrideHandle.ToString(); + parameters["westOverrideHandle"] = profile.regionWestOverrideHandle.ToString(); + parameters["northOverrideHandle"] = profile.regionNorthOverrideHandle.ToString(); + parameters["southOverrideHandle"] = profile.regionSouthOverrideHandle.ToString(); + parameters["regionAssetURI"] = profile.regionAssetURI; + parameters["regionAssetRecvKey"] = profile.regionAssetRecvKey; + parameters["regionAssetSendKey"] = profile.regionAssetSendKey; + parameters["regionUserURI"] = profile.regionUserURI; + parameters["regionUserRecvKey"] = profile.regionUserRecvKey; + parameters["regionUserSendKey"] = profile.regionUserSendKey; + parameters["regionMapTexture"] = profile.regionMapTextureID.ToString(); + parameters["serverHttpPort"] = profile.httpPort.ToString(); + parameters["serverRemotingPort"] = profile.remotingPort.ToString(); + parameters["owner_uuid"] = profile.owner_uuid.ToString(); + + bool returnval = false; + + try + { + IDbCommand result = database.Query(sql, parameters); + + if (result.ExecuteNonQuery() == 1) + returnval = true; + + result.Dispose(); + } + catch (Exception e) + { + m_log.Error("MSSQLManager : " + e.ToString()); + } + + return returnval; + } + + /// + /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret. + /// + /// The UUID of the challenger + /// The attempted regionHandle of the challenger + /// The secret + /// Whether the secret and regionhandle match the database entry for UUID + override public bool AuthenticateSim(LLUUID uuid, ulong handle, string authkey) + { + bool throwHissyFit = false; // Should be true by 1.0 + + if (throwHissyFit) + throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); + + RegionProfileData data = GetProfileByLLUUID(uuid); + + return (handle == data.regionHandle && authkey == data.regionSecret); + } + + /// + /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region + /// + /// This requires a security audit. + /// + /// + /// + /// + /// + public bool AuthenticateSim(LLUUID uuid, ulong handle, string authhash, string challenge) + { + SHA512Managed HashProvider = new SHA512Managed(); + ASCIIEncoding TextProvider = new ASCIIEncoding(); + + byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge); + byte[] hash = HashProvider.ComputeHash(stream); + return false; + } + + override public ReservationData GetReservationAtPoint(uint x, uint y) + { + return null; + } + } +} diff --git a/OpenSim/Data/MSSQL/MSSQLInventoryData.cs b/OpenSim/Data/MSSQL/MSSQLInventoryData.cs new file mode 100644 index 0000000..1e99e51 --- /dev/null +++ b/OpenSim/Data/MSSQL/MSSQLInventoryData.cs @@ -0,0 +1,728 @@ +/* + * 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.Data; +using System.Data.SqlClient; +using libsecondlife; +using OpenSim.Framework.Console; + +namespace OpenSim.Framework.Data.MSSQL +{ + /// + /// A MySQL interface for the inventory server + /// + public class MSSQLInventoryData : IInventoryData + { + private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// The database manager + /// + private MSSQLManager database; + + /// + /// Loads and initialises this database plugin + /// + public void Initialise() + { + IniFile GridDataMySqlFile = new IniFile("mssql_connection.ini"); + string settingDataSource = GridDataMySqlFile.ParseFileReadValue("data_source"); + string settingInitialCatalog = GridDataMySqlFile.ParseFileReadValue("initial_catalog"); + string settingPersistSecurityInfo = GridDataMySqlFile.ParseFileReadValue("persist_security_info"); + string settingUserId = GridDataMySqlFile.ParseFileReadValue("user_id"); + string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); + + database = + new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, + settingPassword); + TestTables(); + } + + #region Test and initialization code + + private void UpgradeFoldersTable(string tableName) + { + // null as the version, indicates that the table didn't exist + if (tableName == null) + { + database.ExecuteResourceSql("CreateFoldersTable.sql"); + //database.ExecuteResourceSql("UpgradeFoldersTableToVersion2.sql"); + return; + } + } + + private void UpgradeItemsTable(string tableName) + { + // null as the version, indicates that the table didn't exist + if (tableName == null) + { + database.ExecuteResourceSql("CreateItemsTable.sql"); + //database.ExecuteResourceSql("UpgradeItemsTableToVersion2.sql"); + return; + } + } + + private void TestTables() + { + Dictionary tableList = new Dictionary(); + + tableList["inventoryfolders"] = null; + tableList["inventoryitems"] = null; + + database.GetTableVersion(tableList); + + UpgradeFoldersTable(tableList["inventoryfolders"]); + UpgradeItemsTable(tableList["inventoryitems"]); + } + + #endregion + + /// + /// The name of this DB provider + /// + /// Name of DB provider + public string getName() + { + return "MSSQL Inventory Data Interface"; + } + + /// + /// Closes this DB provider + /// + public void Close() + { + // Do nothing. + } + + /// + /// Returns the version of this DB provider + /// + /// A string containing the DB provider + public string getVersion() + { + return database.getVersion(); + } + + /// + /// Returns a list of items in a specified folder + /// + /// The folder to search + /// A list containing inventory items + public List getInventoryInFolder(LLUUID folderID) + { + try + { + lock (database) + { + List items = new List(); + + Dictionary param = new Dictionary(); + param["parentFolderID"] = folderID.ToString(); + + IDbCommand result = + database.Query("SELECT * FROM inventoryitems WHERE parentFolderID = @parentFolderID", param); + IDataReader reader = result.ExecuteReader(); + + while (reader.Read()) + items.Add(readInventoryItem(reader)); + + reader.Close(); + result.Dispose(); + + return items; + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return null; + } + } + + /// + /// Returns a list of the root folders within a users inventory + /// + /// The user whos inventory is to be searched + /// A list of folder objects + public List getUserRootFolders(LLUUID user) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["uuid"] = user.ToString(); + param["zero"] = LLUUID.Zero.ToString(); + + IDbCommand result = + database.Query( + "SELECT * FROM inventoryfolders WHERE parentFolderID = @zero AND agentID = @uuid", param); + IDataReader reader = result.ExecuteReader(); + + List items = new List(); + while (reader.Read()) + items.Add(readInventoryFolder(reader)); + + + reader.Close(); + result.Dispose(); + + return items; + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return null; + } + } + + // see InventoryItemBase.getUserRootFolder + public InventoryFolderBase getUserRootFolder(LLUUID user) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["uuid"] = user.ToString(); + param["zero"] = LLUUID.Zero.ToString(); + + IDbCommand result = + database.Query( + "SELECT * FROM inventoryfolders WHERE parentFolderID = @zero AND agentID = @uuid", param); + IDataReader reader = result.ExecuteReader(); + + List items = new List(); + while (reader.Read()) + items.Add(readInventoryFolder(reader)); + + InventoryFolderBase rootFolder = null; + + // There should only ever be one root folder for a user. However, if there's more + // than one we'll simply use the first one rather than failing. It would be even + // nicer to print some message to this effect, but this feels like it's too low a + // to put such a message out, and it's too minor right now to spare the time to + // suitably refactor. + if (items.Count > 0) + { + rootFolder = items[0]; + } + + reader.Close(); + result.Dispose(); + + return rootFolder; + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return null; + } + } + + /// + /// Returns a list of folders in a users inventory contained within the specified folder + /// + /// The folder to search + /// A list of inventory folders + public List getInventoryFolders(LLUUID parentID) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["parentFolderID"] = parentID.ToString(); + + + IDbCommand result = + database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = @parentFolderID", param); + IDataReader reader = result.ExecuteReader(); + + List items = new List(); + + while (reader.Read()) + items.Add(readInventoryFolder(reader)); + + reader.Close(); + result.Dispose(); + + return items; + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return null; + } + } + + /// + /// Reads a one item from an SQL result + /// + /// The SQL Result + /// the item read + private InventoryItemBase readInventoryItem(IDataReader reader) + { + try + { + InventoryItemBase item = new InventoryItemBase(); + + item.inventoryID = new LLUUID((string) reader["inventoryID"]); + item.assetID = new LLUUID((string) reader["assetID"]); + item.assetType = (int) reader["assetType"]; + item.parentFolderID = new LLUUID((string) reader["parentFolderID"]); + item.avatarID = new LLUUID((string) reader["avatarID"]); + item.inventoryName = (string) reader["inventoryName"]; + item.inventoryDescription = (string) reader["inventoryDescription"]; + item.inventoryNextPermissions = Convert.ToUInt32(reader["inventoryNextPermissions"]); + item.inventoryCurrentPermissions = Convert.ToUInt32(reader["inventoryCurrentPermissions"]); + item.invType = (int) reader["invType"]; + item.creatorsID = new LLUUID((string) reader["creatorID"]); + item.inventoryBasePermissions = Convert.ToUInt32(reader["inventoryBasePermissions"]); + item.inventoryEveryOnePermissions = Convert.ToUInt32(reader["inventoryEveryOnePermissions"]); + return item; + } + catch (SqlException e) + { + m_log.Error(e.ToString()); + } + + return null; + } + + /// + /// Returns a specified inventory item + /// + /// The item to return + /// An inventory item + public InventoryItemBase getInventoryItem(LLUUID itemID) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["inventoryID"] = itemID.ToString(); + + IDbCommand result = + database.Query("SELECT * FROM inventoryitems WHERE inventoryID = @inventoryID", param); + IDataReader reader = result.ExecuteReader(); + + InventoryItemBase item = null; + if (reader.Read()) + item = readInventoryItem(reader); + + reader.Close(); + result.Dispose(); + + return item; + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + } + return null; + } + + /// + /// Reads a list of inventory folders returned by a query. + /// + /// A MySQL Data Reader + /// A List containing inventory folders + protected InventoryFolderBase readInventoryFolder(IDataReader reader) + { + try + { + InventoryFolderBase folder = new InventoryFolderBase(); + folder.agentID = new LLUUID((string) reader["agentID"]); + folder.parentID = new LLUUID((string) reader["parentFolderID"]); + folder.folderID = new LLUUID((string) reader["folderID"]); + folder.name = (string) reader["folderName"]; + folder.type = (short) reader["type"]; + folder.version = (ushort) ((int) reader["version"]); + return folder; + } + catch (Exception e) + { + m_log.Error(e.ToString()); + } + + return null; + } + + /// + /// Returns a specified inventory folder + /// + /// The folder to return + /// A folder class + public InventoryFolderBase getInventoryFolder(LLUUID folderID) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["uuid"] = folderID.ToString(); + + IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE folderID = @uuid", param); + IDataReader reader = result.ExecuteReader(); + + reader.Read(); + InventoryFolderBase folder = readInventoryFolder(reader); + reader.Close(); + result.Dispose(); + + return folder; + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return null; + } + } + + /// + /// Adds a specified item to the database + /// + /// The inventory item + public void addInventoryItem(InventoryItemBase item) + { + if (getInventoryItem(item.inventoryID) != null) + { + updateInventoryItem(item); + return; + } + + string sql = "INSERT INTO inventoryitems"; + sql += + "([inventoryID], [assetID], [assetType], [parentFolderID], [avatarID], [inventoryName], [inventoryDescription], [inventoryNextPermissions], [inventoryCurrentPermissions], [invType], [creatorID], [inventoryBasePermissions], [inventoryEveryOnePermissions]) VALUES "; + sql += + "(@inventoryID, @assetID, @assetType, @parentFolderID, @avatarID, @inventoryName, @inventoryDescription, @inventoryNextPermissions, @inventoryCurrentPermissions, @invType, @creatorID, @inventoryBasePermissions, @inventoryEveryOnePermissions);"; + + try + { + Dictionary param = new Dictionary(); + param["inventoryID"] = item.inventoryID.ToString(); + param["assetID"] = item.assetID.ToString(); + param["assetType"] = item.assetType.ToString(); + param["parentFolderID"] = item.parentFolderID.ToString(); + param["avatarID"] = item.avatarID.ToString(); + param["inventoryName"] = item.inventoryName; + param["inventoryDescription"] = item.inventoryDescription; + param["inventoryNextPermissions"] = item.inventoryNextPermissions.ToString(); + param["inventoryCurrentPermissions"] = item.inventoryCurrentPermissions.ToString(); + param["invType"] = Convert.ToString(item.invType); + param["creatorID"] = item.creatorsID.ToString(); + param["inventoryBasePermissions"] = Convert.ToString(item.inventoryBasePermissions); + param["inventoryEveryOnePermissions"] = Convert.ToString(item.inventoryEveryOnePermissions); + + IDbCommand result = database.Query(sql, param); + result.ExecuteNonQuery(); + result.Dispose(); + } + catch (SqlException e) + { + m_log.Error(e.ToString()); + } + } + + /// + /// Updates the specified inventory item + /// + /// Inventory item to update + public void updateInventoryItem(InventoryItemBase item) + { + SqlCommand command = new SqlCommand("UPDATE inventoryitems set inventoryID = @inventoryID, " + + "assetID = @assetID, " + + "assetType = @assetType" + + "parentFolderID = @parentFolderID" + + "avatarID = @avatarID" + + "inventoryName = @inventoryName" + + "inventoryDescription = @inventoryDescription" + + "inventoryNextPermissions = @inventoryNextPermissions" + + "inventoryCurrentPermissions = @inventoryCurrentPermissions" + + "invType = @invType" + + "creatorID = @creatorID" + + "inventoryBasePermissions = @inventoryBasePermissions" + + "inventoryEveryOnePermissions = @inventoryEveryOnePermissions) where " + + "inventoryID = @keyInventoryID;", database.getConnection()); + SqlParameter param1 = new SqlParameter("@inventoryID", item.inventoryID.ToString()); + SqlParameter param2 = new SqlParameter("@assetID", item.assetID); + SqlParameter param3 = new SqlParameter("@assetType", item.assetType); + SqlParameter param4 = new SqlParameter("@parentFolderID", item.parentFolderID); + SqlParameter param5 = new SqlParameter("@avatarID", item.avatarID); + SqlParameter param6 = new SqlParameter("@inventoryName", item.inventoryName); + SqlParameter param7 = new SqlParameter("@inventoryDescription", item.inventoryDescription); + SqlParameter param8 = new SqlParameter("@inventoryNextPermissions", item.inventoryNextPermissions); + SqlParameter param9 = new SqlParameter("@inventoryCurrentPermissions", item.inventoryCurrentPermissions); + SqlParameter param10 = new SqlParameter("@invType", item.invType); + SqlParameter param11 = new SqlParameter("@creatorID", item.creatorsID); + SqlParameter param12 = new SqlParameter("@inventoryBasePermissions", item.inventoryBasePermissions); + SqlParameter param13 = new SqlParameter("@inventoryEveryOnePermissions", item.inventoryEveryOnePermissions); + SqlParameter param14 = new SqlParameter("@keyInventoryID", item.inventoryID.ToString()); + command.Parameters.Add(param1); + command.Parameters.Add(param2); + command.Parameters.Add(param3); + command.Parameters.Add(param4); + command.Parameters.Add(param5); + command.Parameters.Add(param6); + command.Parameters.Add(param7); + command.Parameters.Add(param8); + command.Parameters.Add(param9); + command.Parameters.Add(param10); + command.Parameters.Add(param11); + command.Parameters.Add(param12); + command.Parameters.Add(param13); + command.Parameters.Add(param14); + + try + { + command.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.Error(e.ToString()); + } + } + + /// + /// + /// + /// + public void deleteInventoryItem(LLUUID itemID) + { + try + { + Dictionary param = new Dictionary(); + param["uuid"] = itemID.ToString(); + + IDbCommand cmd = database.Query("DELETE FROM inventoryitems WHERE inventoryID=@uuid", param); + cmd.ExecuteNonQuery(); + cmd.Dispose(); + } + catch (SqlException e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + } + } + + /// + /// Creates a new inventory folder + /// + /// Folder to create + public void addInventoryFolder(InventoryFolderBase folder) + { + string sql = + "INSERT INTO inventoryfolders ([folderID], [agentID], [parentFolderID], [folderName], [type], [version]) VALUES "; + sql += "(@folderID, @agentID, @parentFolderID, @folderName, @type, @version);"; + + + Dictionary param = new Dictionary(); + param["folderID"] = folder.folderID.ToString(); + param["agentID"] = folder.agentID.ToString(); + param["parentFolderID"] = folder.parentID.ToString(); + param["folderName"] = folder.name; + param["type"] = Convert.ToString(folder.type); + param["version"] = Convert.ToString(folder.version); + + try + { + IDbCommand result = database.Query(sql, param); + result.ExecuteNonQuery(); + result.Dispose(); + } + catch (Exception e) + { + m_log.Error(e.ToString()); + } + } + + /// + /// Updates an inventory folder + /// + /// Folder to update + public void updateInventoryFolder(InventoryFolderBase folder) + { + SqlCommand command = new SqlCommand("UPDATE inventoryfolders set folderID = @folderID, " + + "agentID = @agentID, " + + "parentFolderID = @parentFolderID," + + "folderName = @folderName," + + "type = @type," + + "version = @version where " + + "folderID = @keyFolderID;", database.getConnection()); + SqlParameter param1 = new SqlParameter("@folderID", folder.folderID.ToString()); + SqlParameter param2 = new SqlParameter("@agentID", folder.agentID.ToString()); + SqlParameter param3 = new SqlParameter("@parentFolderID", folder.parentID.ToString()); + SqlParameter param4 = new SqlParameter("@folderName", folder.name); + SqlParameter param5 = new SqlParameter("@type", folder.type); + SqlParameter param6 = new SqlParameter("@version", folder.version); + SqlParameter param7 = new SqlParameter("@keyFolderID", folder.folderID.ToString()); + command.Parameters.Add(param1); + command.Parameters.Add(param2); + command.Parameters.Add(param3); + command.Parameters.Add(param4); + command.Parameters.Add(param5); + command.Parameters.Add(param6); + command.Parameters.Add(param7); + + try + { + command.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.Error(e.ToString()); + } + } + + /// + /// Updates an inventory folder + /// + /// Folder to update + public void moveInventoryFolder(InventoryFolderBase folder) + { + SqlCommand command = new SqlCommand("UPDATE inventoryfolders set folderID = @folderID, " + + "parentFolderID = @parentFolderID," + + "folderID = @keyFolderID;", database.getConnection()); + SqlParameter param1 = new SqlParameter("@folderID", folder.folderID.ToString()); + SqlParameter param2 = new SqlParameter("@parentFolderID", folder.parentID.ToString()); + SqlParameter param3 = new SqlParameter("@keyFolderID", folder.folderID.ToString()); + command.Parameters.Add(param1); + command.Parameters.Add(param2); + command.Parameters.Add(param3); + + try + { + command.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.Error(e.ToString()); + } + } + + /// + /// Append a list of all the child folders of a parent folder + /// + /// list where folders will be appended + /// ID of parent + protected void getInventoryFolders(ref List folders, LLUUID parentID) + { + List subfolderList = getInventoryFolders(parentID); + + foreach (InventoryFolderBase f in subfolderList) + folders.Add(f); + } + + // See IInventoryData + public List getFolderHierarchy(LLUUID parentID) + { + List folders = new List(); + getInventoryFolders(ref folders, parentID); + + for (int i = 0; i < folders.Count; i++) + getInventoryFolders(ref folders, folders[i].folderID); + + return folders; + } + + protected void deleteOneFolder(LLUUID folderID) + { + try + { + Dictionary param = new Dictionary(); + param["folderID"] = folderID.ToString(); + + IDbCommand cmd = database.Query("DELETE FROM inventoryfolders WHERE folderID=@folderID", param); + cmd.ExecuteNonQuery(); + cmd.Dispose(); + } + catch (SqlException e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + } + } + + protected void deleteItemsInFolder(LLUUID folderID) + { + try + { + Dictionary param = new Dictionary(); + param["parentFolderID"] = folderID.ToString(); + + + IDbCommand cmd = + database.Query("DELETE FROM inventoryitems WHERE parentFolderID=@parentFolderID", param); + cmd.ExecuteNonQuery(); + cmd.Dispose(); + } + catch (SqlException e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + } + } + + /// + /// Delete an inventory folder + /// + /// Id of folder to delete + public void deleteInventoryFolder(LLUUID folderID) + { + lock (database) + { + List subFolders = getFolderHierarchy(folderID); + + //Delete all sub-folders + foreach (InventoryFolderBase f in subFolders) + { + deleteOneFolder(f.folderID); + deleteItemsInFolder(f.folderID); + } + + //Delete the actual row + deleteOneFolder(folderID); + deleteItemsInFolder(folderID); + } + } + } +} diff --git a/OpenSim/Data/MSSQL/MSSQLLogData.cs b/OpenSim/Data/MSSQL/MSSQLLogData.cs new file mode 100644 index 0000000..c76af53 --- /dev/null +++ b/OpenSim/Data/MSSQL/MSSQLLogData.cs @@ -0,0 +1,120 @@ +/* + * 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.Collections.Generic; +using System.Data; + +namespace OpenSim.Framework.Data.MSSQL +{ + /// + /// An interface to the log database for MySQL + /// + internal class MSSQLLogData : ILogData + { + /// + /// The database manager + /// + public MSSQLManager database; + + /// + /// Artificial constructor called when the plugin is loaded + /// + public void Initialise() + { + IniFile GridDataMySqlFile = new IniFile("mssql_connection.ini"); + string settingDataSource = GridDataMySqlFile.ParseFileReadValue("data_source"); + string settingInitialCatalog = GridDataMySqlFile.ParseFileReadValue("initial_catalog"); + string settingPersistSecurityInfo = GridDataMySqlFile.ParseFileReadValue("persist_security_info"); + string settingUserId = GridDataMySqlFile.ParseFileReadValue("user_id"); + string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); + + database = + new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, + settingPassword); + + IDbCommand cmd = database.Query("select top 1 * from logs", new Dictionary()); + try + { + cmd.ExecuteNonQuery(); + cmd.Dispose(); + } + catch + { + database.ExecuteResourceSql("Mssql-logs.sql"); + } + + } + + /// + /// Saves a log item to the database + /// + /// The daemon triggering the event + /// The target of the action (region / agent UUID, etc) + /// The method call where the problem occured + /// The arguments passed to the method + /// How critical is this? + /// The message to log + public void saveLog(string serverDaemon, string target, string methodCall, string arguments, int priority, + string logMessage) + { + try + { + database.insertLogRow(serverDaemon, target, methodCall, arguments, priority, logMessage); + } + catch + { + database.Reconnect(); + } + } + + /// + /// Returns the name of this DB provider + /// + /// A string containing the DB provider name + public string getName() + { + return "MSSQL Logdata Interface"; + } + + /// + /// Closes the database provider + /// + public void Close() + { + // Do nothing. + } + + /// + /// Returns the version of this DB provider + /// + /// A string containing the provider version + public string getVersion() + { + return "0.1"; + } + } +} diff --git a/OpenSim/Data/MSSQL/MSSQLManager.cs b/OpenSim/Data/MSSQL/MSSQLManager.cs new file mode 100644 index 0000000..efe62be --- /dev/null +++ b/OpenSim/Data/MSSQL/MSSQLManager.cs @@ -0,0 +1,529 @@ +/* + * 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.Data; +using System.Data.SqlClient; +using System.IO; +using System.Reflection; +using libsecondlife; +using OpenSim.Framework.Console; + +namespace OpenSim.Framework.Data.MSSQL +{ + /// + /// A management class for the MS SQL Storage Engine + /// + public class MSSQLManager + { + private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// The database connection object + /// + private IDbConnection dbcon; + + /// + /// Connection string for ADO.net + /// + private readonly string connectionString; + + public MSSQLManager(string dataSource, string initialCatalog, string persistSecurityInfo, string userId, + string password) + { + connectionString = "Data Source=" + dataSource + ";Initial Catalog=" + initialCatalog + + ";Persist Security Info=" + persistSecurityInfo + ";User ID=" + userId + ";Password=" + + password + ";"; + dbcon = new SqlConnection(connectionString); + dbcon.Open(); + } + + //private DataTable createRegionsTable() + //{ + // DataTable regions = new DataTable("regions"); + + // createCol(regions, "regionHandle", typeof (ulong)); + // createCol(regions, "regionName", typeof (String)); + // createCol(regions, "uuid", typeof (String)); + + // createCol(regions, "regionRecvKey", typeof (String)); + // createCol(regions, "regionSecret", typeof (String)); + // createCol(regions, "regionSendKey", typeof (String)); + + // createCol(regions, "regionDataURI", typeof (String)); + // createCol(regions, "serverIP", typeof (String)); + // createCol(regions, "serverPort", typeof (String)); + // createCol(regions, "serverURI", typeof (String)); + + + // createCol(regions, "locX", typeof (uint)); + // createCol(regions, "locY", typeof (uint)); + // createCol(regions, "locZ", typeof (uint)); + + // createCol(regions, "eastOverrideHandle", typeof (ulong)); + // createCol(regions, "westOverrideHandle", typeof (ulong)); + // createCol(regions, "southOverrideHandle", typeof (ulong)); + // createCol(regions, "northOverrideHandle", typeof (ulong)); + + // createCol(regions, "regionAssetURI", typeof (String)); + // createCol(regions, "regionAssetRecvKey", typeof (String)); + // createCol(regions, "regionAssetSendKey", typeof (String)); + + // createCol(regions, "regionUserURI", typeof (String)); + // createCol(regions, "regionUserRecvKey", typeof (String)); + // createCol(regions, "regionUserSendKey", typeof (String)); + + // createCol(regions, "regionMapTexture", typeof (String)); + // createCol(regions, "serverHttpPort", typeof (String)); + // createCol(regions, "serverRemotingPort", typeof (uint)); + + // // Add in contraints + // regions.PrimaryKey = new DataColumn[] {regions.Columns["UUID"]}; + // return regions; + //} + + protected static void createCol(DataTable dt, string name, Type type) + { + DataColumn col = new DataColumn(name, type); + dt.Columns.Add(col); + } + + protected static string defineTable(DataTable dt) + { + string sql = "create table " + dt.TableName + "("; + string subsql = String.Empty; + foreach (DataColumn col in dt.Columns) + { + if (subsql.Length > 0) + { + // a map function would rock so much here + subsql += ",\n"; + } + + subsql += col.ColumnName + " " + SqlType(col.DataType); + if (col == dt.PrimaryKey[0]) + { + subsql += " primary key"; + } + } + sql += subsql; + sql += ")"; + return sql; + } + + + // this is something we'll need to implement for each db + // slightly differently. + public static string SqlType(Type type) + { + if (type == typeof(String)) + { + return "varchar(255)"; + } + else if (type == typeof(Int32)) + { + return "integer"; + } + else if (type == typeof(Double)) + { + return "float"; + } + else if (type == typeof(Byte[])) + { + return "image"; + } + else + { + return "varchar(255)"; + } + } + + /// + /// Shuts down the database connection + /// + public void Close() + { + dbcon.Close(); + dbcon = null; + } + + /// + /// Reconnects to the database + /// + public void Reconnect() + { + lock (dbcon) + { + 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()); + } + } + } + + /// + /// Runs a query with protection against SQL Injection by using parameterised input. + /// + /// The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y + /// The parameters - index so that @y is indexed as 'y' + /// A Sql DB Command + public IDbCommand Query(string sql, Dictionary parameters) + { + SqlCommand dbcommand = (SqlCommand)dbcon.CreateCommand(); + dbcommand.CommandText = sql; + foreach (KeyValuePair param in parameters) + { + dbcommand.Parameters.AddWithValue(param.Key, param.Value); + } + + return (IDbCommand)dbcommand; + } + + /// + /// Runs a database reader object and returns a region row + /// + /// An active database reader + /// A region row + public RegionProfileData getRegionRow(IDataReader reader) + { + RegionProfileData regionprofile = new RegionProfileData(); + + if (reader.Read()) + { + // Region Main + regionprofile.regionHandle = Convert.ToUInt64(reader["regionHandle"]); + regionprofile.regionName = (string)reader["regionName"]; + regionprofile.UUID = new LLUUID((string)reader["uuid"]); + + // Secrets + regionprofile.regionRecvKey = (string)reader["regionRecvKey"]; + regionprofile.regionSecret = (string)reader["regionSecret"]; + regionprofile.regionSendKey = (string)reader["regionSendKey"]; + + // Region Server + regionprofile.regionDataURI = (string)reader["regionDataURI"]; + regionprofile.regionOnline = false; // Needs to be pinged before this can be set. + regionprofile.serverIP = (string)reader["serverIP"]; + regionprofile.serverPort = Convert.ToUInt32(reader["serverPort"]); + regionprofile.serverURI = (string)reader["serverURI"]; + regionprofile.httpPort = Convert.ToUInt32(reader["serverHttpPort"]); + regionprofile.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"]); + + + // Location + regionprofile.regionLocX = Convert.ToUInt32(reader["locX"]); + regionprofile.regionLocY = Convert.ToUInt32(reader["locY"]); + regionprofile.regionLocZ = Convert.ToUInt32(reader["locZ"]); + + // Neighbours - 0 = No Override + regionprofile.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"]); + regionprofile.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"]); + regionprofile.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"]); + regionprofile.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"]); + + // Assets + regionprofile.regionAssetURI = (string)reader["regionAssetURI"]; + regionprofile.regionAssetRecvKey = (string)reader["regionAssetRecvKey"]; + regionprofile.regionAssetSendKey = (string)reader["regionAssetSendKey"]; + + // Userserver + regionprofile.regionUserURI = (string)reader["regionUserURI"]; + regionprofile.regionUserRecvKey = (string)reader["regionUserRecvKey"]; + regionprofile.regionUserSendKey = (string)reader["regionUserSendKey"]; + try + { + regionprofile.owner_uuid = new LLUUID((string)reader["owner_uuid"]); + } + catch(Exception) + {} + // World Map Addition + string tempRegionMap = reader["regionMapTexture"].ToString(); + if (tempRegionMap != String.Empty) + { + regionprofile.regionMapTextureID = new LLUUID(tempRegionMap); + } + else + { + regionprofile.regionMapTextureID = new LLUUID(); + } + } + else + { + reader.Close(); + throw new Exception("No rows to return"); + } + return regionprofile; + } + + /// + /// Reads a user profile from an active data reader + /// + /// An active database reader + /// A user profile + public UserProfileData readUserRow(IDataReader reader) + { + UserProfileData retval = new UserProfileData(); + + if (reader.Read()) + { + retval.UUID = new LLUUID((string)reader["UUID"]); + retval.username = (string)reader["username"]; + retval.surname = (string)reader["lastname"]; + + retval.passwordHash = (string)reader["passwordHash"]; + retval.passwordSalt = (string)reader["passwordSalt"]; + + retval.homeRegion = Convert.ToUInt64(reader["homeRegion"].ToString()); + retval.homeLocation = new LLVector3( + Convert.ToSingle(reader["homeLocationX"].ToString()), + Convert.ToSingle(reader["homeLocationY"].ToString()), + Convert.ToSingle(reader["homeLocationZ"].ToString())); + retval.homeLookAt = new LLVector3( + Convert.ToSingle(reader["homeLookAtX"].ToString()), + Convert.ToSingle(reader["homeLookAtY"].ToString()), + Convert.ToSingle(reader["homeLookAtZ"].ToString())); + + retval.created = Convert.ToInt32(reader["created"].ToString()); + retval.lastLogin = Convert.ToInt32(reader["lastLogin"].ToString()); + + retval.userInventoryURI = (string)reader["userInventoryURI"]; + retval.userAssetURI = (string)reader["userAssetURI"]; + + retval.profileCanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString()); + retval.profileWantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString()); + + retval.profileAboutText = (string)reader["profileAboutText"]; + retval.profileFirstText = (string)reader["profileFirstText"]; + + retval.profileImage = new LLUUID((string)reader["profileImage"]); + retval.profileFirstImage = new LLUUID((string)reader["profileFirstImage"]); + retval.webLoginKey = new LLUUID((string)reader["webLoginKey"]); + } + else + { + return null; + } + return retval; + } + + /// + /// Reads an agent row from a database reader + /// + /// An active database reader + /// A user session agent + public UserAgentData readAgentRow(IDataReader reader) + { + UserAgentData retval = new UserAgentData(); + + if (reader.Read()) + { + // Agent IDs + retval.UUID = new LLUUID((string)reader["UUID"]); + retval.sessionID = new LLUUID((string)reader["sessionID"]); + retval.secureSessionID = new LLUUID((string)reader["secureSessionID"]); + + // Agent Who? + retval.agentIP = (string)reader["agentIP"]; + retval.agentPort = Convert.ToUInt32(reader["agentPort"].ToString()); + retval.agentOnline = Convert.ToBoolean(reader["agentOnline"].ToString()); + + // Login/Logout times (UNIX Epoch) + retval.loginTime = Convert.ToInt32(reader["loginTime"].ToString()); + retval.logoutTime = Convert.ToInt32(reader["logoutTime"].ToString()); + + // Current position + retval.currentRegion = (string)reader["currentRegion"]; + retval.currentHandle = Convert.ToUInt64(reader["currentHandle"].ToString()); + LLVector3.TryParse((string)reader["currentPos"], out retval.currentPos); + } + else + { + return null; + } + return retval; + } + + public AssetBase getAssetRow(IDataReader reader) + { + AssetBase asset = new AssetBase(); + if (reader.Read()) + { + // Region Main + + asset = new AssetBase(); + asset.Data = (byte[])reader["data"]; + asset.Description = (string)reader["description"]; + asset.FullID = new LLUUID((string)reader["id"]); + asset.InvType = Convert.ToSByte(reader["invType"]); + asset.Local = Convert.ToBoolean(reader["local"]); // ((sbyte)reader["local"]) != 0 ? true : false; + asset.Name = (string)reader["name"]; + asset.Type = Convert.ToSByte(reader["assetType"]); + } + else + { + return null; // throw new Exception("No rows to return"); + } + return asset; + } + + + /// + /// Inserts a new row into the log database + /// + /// The daemon which triggered this event + /// Who were we operating on when this occured (region UUID, user UUID, etc) + /// The method call where the problem occured + /// The arguments passed to the method + /// How critical is this? + /// Extra message info + /// Saved successfully? + public bool insertLogRow(string serverDaemon, string target, string methodCall, string arguments, int priority, + string logMessage) + { + string sql = "INSERT INTO logs ([target], [server], [method], [arguments], [priority], [message]) VALUES "; + sql += "(@target, @server, @method, @arguments, @priority, @message);"; + + Dictionary parameters = new Dictionary(); + parameters["server"] = serverDaemon; + parameters["target"] = target; + parameters["method"] = methodCall; + parameters["arguments"] = arguments; + parameters["priority"] = priority.ToString(); + parameters["message"] = logMessage; + + bool returnval = false; + + try + { + IDbCommand result = Query(sql, parameters); + + if (result.ExecuteNonQuery() == 1) + returnval = true; + + result.Dispose(); + } + catch (Exception e) + { + m_log.Error(e.ToString()); + return false; + } + + return returnval; + } + + /// + /// Execute a SQL statement stored in a resource, as a string + /// + /// + public void ExecuteResourceSql(string name) + { + SqlCommand cmd = new SqlCommand(getResourceString(name), (SqlConnection)dbcon); + cmd.ExecuteNonQuery(); + cmd.Dispose(); + } + + public SqlConnection getConnection() + { + return (SqlConnection)dbcon; + } + + /// + /// Given a list of tables, return the version of the tables, as seen in the database + /// + /// + public void GetTableVersion(Dictionary tableList) + { + lock (dbcon) + { + Dictionary param = new Dictionary(); + param["dbname"] = dbcon.Database; + IDbCommand tablesCmd = + Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG=@dbname", param); + using (IDataReader tables = tablesCmd.ExecuteReader()) + { + while (tables.Read()) + { + try + { + string tableName = (string)tables["TABLE_NAME"]; + if (tableList.ContainsKey(tableName)) + tableList[tableName] = tableName; + } + catch (Exception e) + { + m_log.Error(e.ToString()); + } + } + tables.Close(); + } + } + } + + private string getResourceString(string name) + { + Assembly assem = GetType().Assembly; + string[] names = assem.GetManifestResourceNames(); + + foreach (string s in names) + if (s.EndsWith(name)) + using (Stream resource = assem.GetManifestResourceStream(s)) + { + using (StreamReader resourceReader = new StreamReader(resource)) + { + string resourceString = resourceReader.ReadToEnd(); + return resourceString; + } + } + throw new Exception(string.Format("Resource '{0}' was not found", name)); + } + + /// + /// Returns the version of this DB provider + /// + /// A string containing the DB provider + public string getVersion() + { + Module module = GetType().Module; + string dllName = module.Assembly.ManifestModule.Name; + Version dllVersion = module.Assembly.GetName().Version; + + + return + string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, + dllVersion.Revision); + } + } +} diff --git a/OpenSim/Data/MSSQL/MSSQLUserData.cs b/OpenSim/Data/MSSQL/MSSQLUserData.cs new file mode 100644 index 0000000..be0417d --- /dev/null +++ b/OpenSim/Data/MSSQL/MSSQLUserData.cs @@ -0,0 +1,771 @@ +/* + * 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.Data; +using System.Data.SqlClient; +using libsecondlife; +using OpenSim.Framework.Console; + +namespace OpenSim.Framework.Data.MSSQL +{ + /// + /// A database interface class to a user profile storage system + /// + public class MSSQLUserData : UserDataBase + { + private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// Database manager for MySQL + /// + public MSSQLManager database; + + private string m_agentsTableName; + private string m_usersTableName; + private string m_userFriendsTableName; + + /// + /// Loads and initialises the MySQL storage plugin + /// + override public void Initialise() + { + // Load from an INI file connection details + // TODO: move this to XML? + IniFile iniFile = new IniFile("mssql_connection.ini"); + string settingDataSource = iniFile.ParseFileReadValue("data_source"); + string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog"); + string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info"); + string settingUserId = iniFile.ParseFileReadValue("user_id"); + string settingPassword = iniFile.ParseFileReadValue("password"); + + m_usersTableName = iniFile.ParseFileReadValue("userstablename"); + if (m_usersTableName == null) + { + m_usersTableName = "users"; + } + + m_userFriendsTableName = iniFile.ParseFileReadValue("userfriendstablename"); + if (m_userFriendsTableName == null) + { + m_userFriendsTableName = "userfriends"; + } + + m_agentsTableName = iniFile.ParseFileReadValue("agentstablename"); + if (m_agentsTableName == null) + { + m_agentsTableName = "agents"; + } + + database = + new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, + settingPassword); + + TestTables(); + } + + private bool TestTables() + { + IDbCommand cmd; + + cmd = database.Query("select top 1 * from " + m_usersTableName, new Dictionary()); + try + { + cmd.ExecuteNonQuery(); + } + catch + { + database.ExecuteResourceSql("Mssql-users.sql"); + } + + cmd = database.Query("select top 1 * from " + m_agentsTableName, new Dictionary()); + try + { + cmd.ExecuteNonQuery(); + } + catch + { + database.ExecuteResourceSql("Mssql-agents.sql"); + } + + cmd = database.Query("select top 1 * from " + m_userFriendsTableName, new Dictionary()); + try + { + cmd.ExecuteNonQuery(); + } + catch + { + database.ExecuteResourceSql("CreateUserFriendsTable.sql"); + } + + return true; + } + /// + /// Searches the database for a specified user profile by name components + /// + /// The first part of the account name + /// The second part of the account name + /// A user profile + override public UserProfileData GetUserByName(string user, string last) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["first"] = user; + param["second"] = last; + + IDbCommand result = + database.Query("SELECT * FROM " + m_usersTableName + " WHERE username = @first AND lastname = @second", param); + IDataReader reader = result.ExecuteReader(); + + UserProfileData row = database.readUserRow(reader); + + reader.Close(); + result.Dispose(); + + return row; + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return null; + } + } + + #region User Friends List Data + + override public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms) + { + int dtvalue = Util.UnixTimeSinceEpoch(); + + Dictionary param = new Dictionary(); + param["@ownerID"] = friendlistowner.UUID.ToString(); + param["@friendID"] = friend.UUID.ToString(); + param["@friendPerms"] = perms.ToString(); + param["@datetimestamp"] = dtvalue.ToString(); + + try + { + lock (database) + { + IDbCommand adder = + database.Query( + "INSERT INTO " + m_userFriendsTableName + " " + + "(ownerID,friendID,friendPerms,datetimestamp) " + + "VALUES " + + "(@ownerID,@friendID,@friendPerms,@datetimestamp)", + param); + + adder.ExecuteNonQuery(); + + adder = + database.Query( + "INSERT INTO " + m_userFriendsTableName + " " + + "(ownerID,friendID,friendPerms,datetimestamp) " + + "VALUES " + + "(@friendID,@ownerID,@friendPerms,@datetimestamp)", + param); + adder.ExecuteNonQuery(); + + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return; + } + } + + override public void RemoveUserFriend(LLUUID friendlistowner, LLUUID friend) + { + Dictionary param = new Dictionary(); + param["@ownerID"] = friendlistowner.UUID.ToString(); + param["@friendID"] = friend.UUID.ToString(); + + + try + { + lock (database) + { + IDbCommand updater = + database.Query( + "delete from " + m_userFriendsTableName + " where ownerID = @ownerID and friendID = @friendID", + param); + updater.ExecuteNonQuery(); + + updater = + database.Query( + "delete from " + m_userFriendsTableName + " where ownerID = @friendID and friendID = @ownerID", + param); + updater.ExecuteNonQuery(); + + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return; + } + } + + override public void UpdateUserFriendPerms(LLUUID friendlistowner, LLUUID friend, uint perms) + { + Dictionary param = new Dictionary(); + param["@ownerID"] = friendlistowner.UUID.ToString(); + param["@friendID"] = friend.UUID.ToString(); + param["@friendPerms"] = perms.ToString(); + + + try + { + lock (database) + { + IDbCommand updater = + database.Query( + "update " + m_userFriendsTableName + + " SET friendPerms = @friendPerms " + + "where ownerID = @ownerID and friendID = @friendID", + param); + + updater.ExecuteNonQuery(); + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return; + } + } + + + override public List GetUserFriendList(LLUUID friendlistowner) + { + List Lfli = new List(); + + Dictionary param = new Dictionary(); + param["@ownerID"] = friendlistowner.UUID.ToString(); + + try + { + lock (database) + { + //Left Join userfriends to itself + IDbCommand result = + database.Query( + "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", + param); + IDataReader reader = result.ExecuteReader(); + + + while (reader.Read()) + { + FriendListItem fli = new FriendListItem(); + fli.FriendListOwner = new LLUUID((string)reader["ownerID"]); + fli.Friend = new LLUUID((string)reader["friendID"]); + fli.FriendPerms = (uint)Convert.ToInt32(reader["friendPerms"]); + + // This is not a real column in the database table, it's a joined column from the opposite record + fli.FriendListOwnerPerms = (uint)Convert.ToInt32(reader["ownerperms"]); + + Lfli.Add(fli); + } + reader.Close(); + result.Dispose(); + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return Lfli; + } + + return Lfli; + } + + #endregion + + override public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid) + { + m_log.Info("[USER]: Stub UpdateUserCUrrentRegion called"); + } + + + + override public List GeneratePickerResults(LLUUID queryID, string query) + { + List returnlist = new List(); + string[] querysplit; + querysplit = query.Split(' '); + if (querysplit.Length == 2) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["first"] = querysplit[0]; + param["second"] = querysplit[1]; + + IDbCommand result = + database.Query( + "SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username = @first AND lastname = @second", + param); + IDataReader reader = result.ExecuteReader(); + + + while (reader.Read()) + { + Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar(); + user.AvatarID = new LLUUID((string)reader["UUID"]); + user.firstName = (string)reader["username"]; + user.lastName = (string)reader["lastname"]; + returnlist.Add(user); + } + reader.Close(); + result.Dispose(); + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return returnlist; + } + } + else if (querysplit.Length == 1) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["first"] = querysplit[0]; + + IDbCommand result = + database.Query( + "SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username = @first OR lastname = @first", + param); + IDataReader reader = result.ExecuteReader(); + + + while (reader.Read()) + { + Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar(); + user.AvatarID = new LLUUID((string)reader["UUID"]); + user.firstName = (string)reader["username"]; + user.lastName = (string)reader["lastname"]; + returnlist.Add(user); + } + reader.Close(); + result.Dispose(); + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return returnlist; + } + } + return returnlist; + } + + // See IUserData + override public UserProfileData GetUserByUUID(LLUUID uuid) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["uuid"] = uuid.ToString(); + + IDbCommand result = database.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = @uuid", param); + IDataReader reader = result.ExecuteReader(); + + UserProfileData row = database.readUserRow(reader); + + reader.Close(); + result.Dispose(); + + return row; + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return null; + } + } + + /// + /// Returns a user session searching by name + /// + /// The account name + /// The users session + override public UserAgentData GetAgentByName(string name) + { + return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]); + } + + /// + /// Returns a user session by account name + /// + /// First part of the users account name + /// Second part of the users account name + /// The users session + override public UserAgentData GetAgentByName(string user, string last) + { + UserProfileData profile = GetUserByName(user, last); + return GetAgentByUUID(profile.UUID); + } + + /// + /// Returns an agent session by account UUID + /// + /// The accounts UUID + /// The users session + override public UserAgentData GetAgentByUUID(LLUUID uuid) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["uuid"] = uuid.ToString(); + + IDbCommand result = database.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = @uuid", param); + IDataReader reader = result.ExecuteReader(); + + UserAgentData row = database.readAgentRow(reader); + + reader.Close(); + result.Dispose(); + + return row; + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + return null; + } + } + override public void StoreWebLoginKey(LLUUID AgentID, LLUUID WebLoginKey) + { + UserProfileData user = GetUserByUUID(AgentID); + user.webLoginKey = WebLoginKey; + UpdateUserProfile(user); + + } + /// + /// Creates a new users profile + /// + /// The user profile to create + override public void AddNewUserProfile(UserProfileData user) + { + try + { + lock (database) + { + InsertUserRow(user.UUID, user.username, user.surname, user.passwordHash, user.passwordSalt, + user.homeRegion, user.homeLocation.X, user.homeLocation.Y, + user.homeLocation.Z, + user.homeLookAt.X, user.homeLookAt.Y, user.homeLookAt.Z, user.created, + user.lastLogin, user.userInventoryURI, user.userAssetURI, + user.profileCanDoMask, user.profileWantDoMask, + user.profileAboutText, user.profileFirstText, user.profileImage, + user.profileFirstImage, user.webLoginKey); + } + } + catch (Exception e) + { + database.Reconnect(); + m_log.Error(e.ToString()); + } + } + + /// + /// Creates a new user and inserts it into the database + /// + /// User ID + /// First part of the login + /// Second part of the login + /// A salted hash of the users password + /// The salt used for the password hash + /// A regionHandle of the users home region + /// Home region position vector + /// Home region position vector + /// Home region position vector + /// Home region 'look at' vector + /// Home region 'look at' vector + /// Home region 'look at' vector + /// Account created (unix timestamp) + /// Last login (unix timestamp) + /// Users inventory URI + /// Users asset URI + /// I can do mask + /// I want to do mask + /// Profile text + /// Firstlife text + /// UUID for profile image + /// UUID for firstlife image + /// Success? + private bool InsertUserRow(LLUUID uuid, string username, string lastname, string passwordHash, + string passwordSalt, UInt64 homeRegion, float homeLocX, float homeLocY, float homeLocZ, + float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin, + string inventoryURI, string assetURI, uint canDoMask, uint wantDoMask, + string aboutText, string firstText, + LLUUID profileImage, LLUUID firstImage, LLUUID webLoginKey) + { + string sql = "INSERT INTO "+m_usersTableName; + sql += " ([UUID], [username], [lastname], [passwordHash], [passwordSalt], [homeRegion], "; + sql += + "[homeLocationX], [homeLocationY], [homeLocationZ], [homeLookAtX], [homeLookAtY], [homeLookAtZ], [created], "; + sql += + "[lastLogin], [userInventoryURI], [userAssetURI], [profileCanDoMask], [profileWantDoMask], [profileAboutText], "; + sql += "[profileFirstText], [profileImage], [profileFirstImage], [webLoginKey]) VALUES "; + + sql += "(@UUID, @username, @lastname, @passwordHash, @passwordSalt, @homeRegion, "; + sql += + "@homeLocationX, @homeLocationY, @homeLocationZ, @homeLookAtX, @homeLookAtY, @homeLookAtZ, @created, "; + sql += + "@lastLogin, @userInventoryURI, @userAssetURI, @profileCanDoMask, @profileWantDoMask, @profileAboutText, "; + sql += "@profileFirstText, @profileImage, @profileFirstImage, @webLoginKey);"; + + Dictionary parameters = new Dictionary(); + parameters["UUID"] = uuid.ToString(); + parameters["username"] = username.ToString(); + parameters["lastname"] = lastname.ToString(); + parameters["passwordHash"] = passwordHash.ToString(); + parameters["passwordSalt"] = passwordSalt.ToString(); + parameters["homeRegion"] = homeRegion.ToString(); + parameters["homeLocationX"] = homeLocX.ToString(); + parameters["homeLocationY"] = homeLocY.ToString(); + parameters["homeLocationZ"] = homeLocZ.ToString(); + parameters["homeLookAtX"] = homeLookAtX.ToString(); + parameters["homeLookAtY"] = homeLookAtY.ToString(); + parameters["homeLookAtZ"] = homeLookAtZ.ToString(); + parameters["created"] = created.ToString(); + parameters["lastLogin"] = lastlogin.ToString(); + parameters["userInventoryURI"] = String.Empty; + parameters["userAssetURI"] = String.Empty; + parameters["profileCanDoMask"] = "0"; + parameters["profileWantDoMask"] = "0"; + parameters["profileAboutText"] = aboutText; + parameters["profileFirstText"] = firstText; + parameters["profileImage"] = profileImage.ToString(); + parameters["profileFirstImage"] = firstImage.ToString(); + parameters["webLoginKey"] = LLUUID.Random().ToString(); + + bool returnval = false; + + try + { + IDbCommand result = database.Query(sql, parameters); + + if (result.ExecuteNonQuery() == 1) + returnval = true; + + result.Dispose(); + } + catch (Exception e) + { + m_log.Error(e.ToString()); + return false; + } + + return returnval; + } + + /// + /// Creates a new agent + /// + /// The agent to create + override public void AddNewUserAgent(UserAgentData agent) + { + // Do nothing. + } + + + override public bool UpdateUserProfile(UserProfileData user) + { + SqlCommand command = new SqlCommand("UPDATE " + m_usersTableName + " set UUID = @uuid, " + + "username = @username, " + + "lastname = @lastname," + + "passwordHash = @passwordHash," + + "passwordSalt = @passwordSalt," + + "homeRegion = @homeRegion," + + "homeLocationX = @homeLocationX," + + "homeLocationY = @homeLocationY," + + "homeLocationZ = @homeLocationZ," + + "homeLookAtX = @homeLookAtX," + + "homeLookAtY = @homeLookAtY," + + "homeLookAtZ = @homeLookAtZ," + + "created = @created," + + "lastLogin = @lastLogin," + + "userInventoryURI = @userInventoryURI," + + "userAssetURI = @userAssetURI," + + "profileCanDoMask = @profileCanDoMask," + + "profileWantDoMask = @profileWantDoMask," + + "profileAboutText = @profileAboutText," + + "profileFirstText = @profileFirstText," + + "profileImage = @profileImage," + + "profileFirstImage = @profileFirstImage, " + + "webLoginKey = @webLoginKey where " + + "UUID = @keyUUUID;", database.getConnection()); + SqlParameter param1 = new SqlParameter("@uuid", user.UUID.ToString()); + SqlParameter param2 = new SqlParameter("@username", user.username); + SqlParameter param3 = new SqlParameter("@lastname", user.surname); + SqlParameter param4 = new SqlParameter("@passwordHash", user.passwordHash); + SqlParameter param5 = new SqlParameter("@passwordSalt", user.passwordSalt); + SqlParameter param6 = new SqlParameter("@homeRegion", Convert.ToInt64(user.homeRegion)); + SqlParameter param7 = new SqlParameter("@homeLocationX", user.homeLocation.X); + SqlParameter param8 = new SqlParameter("@homeLocationY", user.homeLocation.Y); + SqlParameter param9 = new SqlParameter("@homeLocationZ", user.homeLocation.Y); + SqlParameter param10 = new SqlParameter("@homeLookAtX", user.homeLookAt.X); + SqlParameter param11 = new SqlParameter("@homeLookAtY", user.homeLookAt.Y); + SqlParameter param12 = new SqlParameter("@homeLookAtZ", user.homeLookAt.Z); + SqlParameter param13 = new SqlParameter("@created", Convert.ToInt32(user.created)); + SqlParameter param14 = new SqlParameter("@lastLogin", Convert.ToInt32(user.lastLogin)); + SqlParameter param15 = new SqlParameter("@userInventoryURI", user.userInventoryURI); + SqlParameter param16 = new SqlParameter("@userAssetURI", user.userAssetURI); + SqlParameter param17 = new SqlParameter("@profileCanDoMask", Convert.ToInt32(user.profileCanDoMask)); + SqlParameter param18 = new SqlParameter("@profileWantDoMask", Convert.ToInt32(user.profileWantDoMask)); + SqlParameter param19 = new SqlParameter("@profileAboutText", user.profileAboutText); + SqlParameter param20 = new SqlParameter("@profileFirstText", user.profileFirstText); + SqlParameter param21 = new SqlParameter("@profileImage", user.profileImage.ToString()); + SqlParameter param22 = new SqlParameter("@profileFirstImage", user.profileFirstImage.ToString()); + SqlParameter param23 = new SqlParameter("@keyUUUID", user.UUID.ToString()); + SqlParameter param24 = new SqlParameter("@webLoginKey", user.webLoginKey.UUID.ToString()); + command.Parameters.Add(param1); + command.Parameters.Add(param2); + command.Parameters.Add(param3); + command.Parameters.Add(param4); + command.Parameters.Add(param5); + command.Parameters.Add(param6); + command.Parameters.Add(param7); + command.Parameters.Add(param8); + command.Parameters.Add(param9); + command.Parameters.Add(param10); + command.Parameters.Add(param11); + command.Parameters.Add(param12); + command.Parameters.Add(param13); + command.Parameters.Add(param14); + command.Parameters.Add(param15); + command.Parameters.Add(param16); + command.Parameters.Add(param17); + command.Parameters.Add(param18); + command.Parameters.Add(param19); + command.Parameters.Add(param20); + command.Parameters.Add(param21); + command.Parameters.Add(param22); + command.Parameters.Add(param23); + command.Parameters.Add(param24); + try + { + int affected = command.ExecuteNonQuery(); + if (affected != 0) + { + return true; + } + else + { + return false; + } + } + catch (Exception e) + { + m_log.Error(e.ToString()); + } + return false; + } + + /// + /// Performs a money transfer request between two accounts + /// + /// The senders account ID + /// The receivers account ID + /// The amount to transfer + /// Success? + override public bool MoneyTransferRequest(LLUUID from, LLUUID to, uint amount) + { + return false; + } + + /// + /// Performs an inventory transfer request between two accounts + /// + /// TODO: Move to inventory server + /// The senders account ID + /// The receivers account ID + /// The item to transfer + /// Success? + override public bool InventoryTransferRequest(LLUUID from, LLUUID to, LLUUID item) + { + return false; + } + + /// + /// Database provider name + /// + /// Provider name + override public string getName() + { + return "MSSQL Userdata Interface"; + } + + /// + /// Database provider version + /// + /// provider version + override public string GetVersion() + { + return database.getVersion(); + } + + /// + /// Not implemented + /// + /// + public void runQuery(string query) + { + } + } +} diff --git a/OpenSim/Data/MSSQL/Properties/AssemblyInfo.cs b/OpenSim/Data/MSSQL/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f6ac328 --- /dev/null +++ b/OpenSim/Data/MSSQL/Properties/AssemblyInfo.cs @@ -0,0 +1,65 @@ +/* + * 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.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly : AssemblyTitle("OpenSim.Framework.Data.MSSQL")] +[assembly : AssemblyDescription("")] +[assembly : AssemblyConfiguration("")] +[assembly : AssemblyCompany("")] +[assembly : AssemblyProduct("OpenSim.Framework.Data.MSSQL")] +[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2008")] +[assembly : AssemblyTrademark("")] +[assembly : AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. + +[assembly : ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly : Guid("0e1c1ca4-2cf2-4315-b0e7-432c02feea8a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly : AssemblyVersion("1.0.0.0")] +[assembly : AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Data/MSSQL/Resources/AvatarAppearance.sql b/OpenSim/Data/MSSQL/Resources/AvatarAppearance.sql new file mode 100644 index 0000000..ccefba2 --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/AvatarAppearance.sql @@ -0,0 +1,44 @@ +-- +-- Create schema avatar_appearance +-- + +SET ANSI_NULLS ON +SET QUOTED_IDENTIFIER ON +SET ANSI_PADDING ON + +CREATE TABLE [avatarappearance] ( + [UUID] uniqueidentifier NOT NULL, + [Serial] int NOT NULL, + [WearableItem0] uniqueidentifier NOT NULL, + [WearableAsset0] uniqueidentifier NOT NULL, + [WearableItem1] uniqueidentifier NOT NULL, + [WearableAsset1] uniqueidentifier NOT NULL, + [WearableItem2] uniqueidentifier NOT NULL, + [WearableAsset2] uniqueidentifier NOT NULL, + [WearableItem3] uniqueidentifier NOT NULL, + [WearableAsset3] uniqueidentifier NOT NULL, + [WearableItem4] uniqueidentifier NOT NULL, + [WearableAsset4] uniqueidentifier NOT NULL, + [WearableItem5] uniqueidentifier NOT NULL, + [WearableAsset5] uniqueidentifier NOT NULL, + [WearableItem6] uniqueidentifier NOT NULL, + [WearableAsset6] uniqueidentifier NOT NULL, + [WearableItem7] uniqueidentifier NOT NULL, + [WearableAsset7] uniqueidentifier NOT NULL, + [WearableItem8] uniqueidentifier NOT NULL, + [WearableAsset8] uniqueidentifier NOT NULL, + [WearableItem9] uniqueidentifier NOT NULL, + [WearableAsset9] uniqueidentifier NOT NULL, + [WearableItem10] uniqueidentifier NOT NULL, + [WearableAsset10] uniqueidentifier NOT NULL, + [WearableItem11] uniqueidentifier NOT NULL, + [WearableAsset11] uniqueidentifier NOT NULL, + [WearableItem12] uniqueidentifier NOT NULL, + [WearableAsset12] uniqueidentifier NOT NULL + + PRIMARY KEY CLUSTERED ( + [UUID] + ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + +SET ANSI_PADDING OFF diff --git a/OpenSim/Data/MSSQL/Resources/CreateAssetsTable.sql b/OpenSim/Data/MSSQL/Resources/CreateAssetsTable.sql new file mode 100644 index 0000000..c7cb21a --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/CreateAssetsTable.sql @@ -0,0 +1,19 @@ +SET ANSI_NULLS ON +SET QUOTED_IDENTIFIER ON +SET ANSI_PADDING ON +CREATE TABLE [assets] ( + [id] [varchar](36) NOT NULL, + [name] [varchar](64) NOT NULL, + [description] [varchar](64) NOT NULL, + [assetType] [tinyint] NOT NULL, + [invType] [tinyint] NOT NULL, + [local] [tinyint] NOT NULL, + [temporary] [tinyint] NOT NULL, + [data] [image] NOT NULL, +PRIMARY KEY CLUSTERED +( + [id] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + +SET ANSI_PADDING OFF diff --git a/OpenSim/Data/MSSQL/Resources/CreateFoldersTable.sql b/OpenSim/Data/MSSQL/Resources/CreateFoldersTable.sql new file mode 100644 index 0000000..95d183a --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/CreateFoldersTable.sql @@ -0,0 +1,27 @@ +SET ANSI_NULLS ON +SET QUOTED_IDENTIFIER ON +SET ANSI_PADDING ON +CREATE TABLE [inventoryfolders] ( + [folderID] [varchar](36) NOT NULL default '', + [agentID] [varchar](36) default NULL, + [parentFolderID] [varchar](36) default NULL, + [folderName] [varchar](64) default NULL, + [type] [smallint] NOT NULL default 0, + [version] [int] NOT NULL default 0, + PRIMARY KEY CLUSTERED +( + [folderID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX [owner] ON [inventoryfolders] +( + [agentID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX [parent] ON [inventoryfolders] +( + [parentFolderID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +SET ANSI_PADDING OFF diff --git a/OpenSim/Data/MSSQL/Resources/CreateItemsTable.sql b/OpenSim/Data/MSSQL/Resources/CreateItemsTable.sql new file mode 100644 index 0000000..5bb27ba --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/CreateItemsTable.sql @@ -0,0 +1,39 @@ +SET ANSI_NULLS ON + +SET QUOTED_IDENTIFIER ON + +SET ANSI_PADDING ON + +CREATE TABLE [inventoryitems] ( + [inventoryID] [varchar](36) NOT NULL default '', + [assetID] [varchar](36) default NULL, + [assetType] [int] default NULL, + [parentFolderID] [varchar](36) default NULL, + [avatarID] [varchar](36) default NULL, + [inventoryName] [varchar](64) default NULL, + [inventoryDescription] [varchar](128) default NULL, + [inventoryNextPermissions] [int] default NULL, + [inventoryCurrentPermissions] [int] default NULL, + [invType] [int] default NULL, + [creatorID] [varchar](36) default NULL, + [inventoryBasePermissions] [int] NOT NULL default 0, + [inventoryEveryOnePermissions] [int] NOT NULL default 0, + PRIMARY KEY CLUSTERED +( + [inventoryID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + + +CREATE NONCLUSTERED INDEX [owner] ON [inventoryitems] +( + [avatarID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX [folder] ON [inventoryitems] +( + [parentFolderID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +SET ANSI_PADDING OFF + diff --git a/OpenSim/Data/MSSQL/Resources/CreateUserFriendsTable.sql b/OpenSim/Data/MSSQL/Resources/CreateUserFriendsTable.sql new file mode 100644 index 0000000..6f5885e --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/CreateUserFriendsTable.sql @@ -0,0 +1,14 @@ +SET ANSI_NULLS ON + +SET QUOTED_IDENTIFIER ON + +SET ANSI_PADDING ON + +CREATE TABLE [dbo].[userfriends]( +[ownerID] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL, +[friendID] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL, +[friendPerms] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, +[datetimestamp] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL +) ON [PRIMARY] + +SET ANSI_PADDING OFF diff --git a/OpenSim/Data/MSSQL/Resources/Mssql-agents.sql b/OpenSim/Data/MSSQL/Resources/Mssql-agents.sql new file mode 100644 index 0000000..ad53173 --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/Mssql-agents.sql @@ -0,0 +1,37 @@ +SET ANSI_NULLS ON + +SET QUOTED_IDENTIFIER ON + +SET ANSI_PADDING ON + +CREATE TABLE [agents] ( + [UUID] [varchar](36) NOT NULL, + [sessionID] [varchar](36) NOT NULL, + [secureSessionID] [varchar](36) NOT NULL, + [agentIP] [varchar](16) NOT NULL, + [agentPort] [int] NOT NULL, + [agentOnline] [tinyint] NOT NULL, + [loginTime] [int] NOT NULL, + [logoutTime] [int] NOT NULL, + [currentRegion] [varchar](36) NOT NULL, + [currentHandle] [bigint] NOT NULL, + [currentPos] [varchar](64) NOT NULL, + PRIMARY KEY CLUSTERED +( + [UUID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + + +CREATE NONCLUSTERED INDEX [session] ON [agents] +( + [sessionID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX [ssession] ON [agents] +( + [secureSessionID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +SET ANSI_PADDING OFF + diff --git a/OpenSim/Data/MSSQL/Resources/Mssql-logs.sql b/OpenSim/Data/MSSQL/Resources/Mssql-logs.sql new file mode 100644 index 0000000..3b747d8 --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/Mssql-logs.sql @@ -0,0 +1,20 @@ +SET ANSI_NULLS ON + +SET QUOTED_IDENTIFIER ON + +SET ANSI_PADDING ON + +CREATE TABLE [logs] ( + [logID] [int] NOT NULL, + [target] [varchar](36) default NULL, + [server] [varchar](64) default NULL, + [method] [varchar](64) default NULL, + [arguments] [varchar](255) default NULL, + [priority] [int] default NULL, + [message] [ntext], + PRIMARY KEY CLUSTERED +( + [logID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + diff --git a/OpenSim/Data/MSSQL/Resources/Mssql-regions.sql b/OpenSim/Data/MSSQL/Resources/Mssql-regions.sql new file mode 100644 index 0000000..b29a2ab --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/Mssql-regions.sql @@ -0,0 +1,41 @@ +SET ANSI_NULLS ON + +SET QUOTED_IDENTIFIER ON + +SET ANSI_PADDING ON + +CREATE TABLE [dbo].[regions]( + [regionHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionName] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [uuid] [varchar](255) COLLATE Latin1_General_CI_AS NOT NULL, + [regionRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionSecret] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionDataURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [serverIP] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [serverPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [serverURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [locX] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [locY] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [locZ] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [eastOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [westOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [southOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [northOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionAssetURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionAssetRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionAssetSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionUserURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionUserRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionUserSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionMapTexture] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [serverHttpPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [serverRemotingPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [owner_uuid] [varchar](36) COLLATE Latin1_General_CI_AS NULL, +PRIMARY KEY CLUSTERED +( + [uuid] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY] + +SET ANSI_PADDING OFF diff --git a/OpenSim/Data/MSSQL/Resources/Mssql-users.sql b/OpenSim/Data/MSSQL/Resources/Mssql-users.sql new file mode 100644 index 0000000..abcc091 --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/Mssql-users.sql @@ -0,0 +1,42 @@ +SET ANSI_NULLS ON + +SET QUOTED_IDENTIFIER ON + +SET ANSI_PADDING ON + +CREATE TABLE [users] ( + [UUID] [varchar](36) NOT NULL default '', + [username] [varchar](32) NOT NULL, + [lastname] [varchar](32) NOT NULL, + [passwordHash] [varchar](32) NOT NULL, + [passwordSalt] [varchar](32) NOT NULL, + [homeRegion] [bigint] default NULL, + [homeLocationX] [float] default NULL, + [homeLocationY] [float] default NULL, + [homeLocationZ] [float] default NULL, + [homeLookAtX] [float] default NULL, + [homeLookAtY] [float] default NULL, + [homeLookAtZ] [float] default NULL, + [created] [int] NOT NULL, + [lastLogin] [int] NOT NULL, + [userInventoryURI] [varchar](255) default NULL, + [userAssetURI] [varchar](255) default NULL, + [profileCanDoMask] [int] default NULL, + [profileWantDoMask] [int] default NULL, + [profileAboutText] [ntext], + [profileFirstText] [ntext], + [profileImage] [varchar](36) default NULL, + [profileFirstImage] [varchar](36) default NULL, + [webLoginKey] [varchar](36) default NULL, + PRIMARY KEY CLUSTERED +( + [UUID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + + +CREATE NONCLUSTERED INDEX [usernames] ON [users] +( + [username] ASC, + [lastname] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -- cgit v1.1