diff --git a/OpenSim/Data/PGSQL/PGSQLAssetData.cs b/OpenSim/Data/PGSQL/PGSQLAssetData.cs new file mode 100644 index 0000000000..ab748566b9 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLAssetData.cs @@ -0,0 +1,295 @@ +/* + * 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 OpenSimulator 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.Data; +using System.Reflection; +using System.Collections.Generic; +using OpenMetaverse; +using log4net; +using OpenSim.Framework; +using Npgsql; +using NpgsqlTypes; + +namespace OpenSim.Data.PGSQL +{ + /// + /// A PGSQL Interface for the Asset server + /// + public class PGSQLAssetData : AssetDataBase + { + private const string _migrationStore = "AssetStore"; + + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private long m_ticksToEpoch; + /// + /// Database manager + /// + private PGSQLManager m_database; + private string m_connectionString; + + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + + #region IPlugin Members + + override public void Dispose() { } + + /// + /// Initialises asset interface + /// + // [Obsolete("Cannot be default-initialized!")] + override public void Initialise() + { + m_log.Info("[PGSQLAssetData]: " + Name + " cannot be default-initialized!"); + throw new PluginNotInitialisedException(Name); + } + + /// + /// Initialises asset interface + /// + /// + /// a string instead of file, if someone writes the support + /// + /// connect string + override public void Initialise(string connectionString) + { + m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks; + + m_database = new PGSQLManager(connectionString); + m_connectionString = connectionString; + + //New migration to check for DB changes + m_database.CheckMigration(_migrationStore); + } + + /// + /// Database provider version. + /// + override public string Version + { + get { return m_database.getVersion(); } + } + + /// + /// The name of this DB provider. + /// + override public string Name + { + get { return "PGSQL Asset storage engine"; } + } + + #endregion + + #region IAssetDataPlugin Members + + /// + /// Fetch Asset from m_database + /// + /// the asset UUID + /// + override public AssetBase GetAsset(UUID assetID) + { + string sql = "SELECT * FROM assets WHERE id = :id"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("id", assetID)); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if (reader.Read()) + { + AssetBase asset = new AssetBase( + DBGuid.FromDB(reader["id"]), + (string)reader["name"], + Convert.ToSByte(reader["assetType"]), + reader["creatorid"].ToString() + ); + // Region Main + asset.Description = (string)reader["description"]; + asset.Local = Convert.ToBoolean(reader["local"]); + asset.Temporary = Convert.ToBoolean(reader["temporary"]); + asset.Flags = (AssetFlags)(Convert.ToInt32(reader["asset_flags"])); + asset.Data = (byte[])reader["data"]; + return asset; + } + return null; // throw new Exception("No rows to return"); + } + } + } + + /// + /// Create asset in m_database + /// + /// the asset + override public void StoreAsset(AssetBase asset) + { + + string sql = + @"UPDATE assets set name = :name, description = :description, " + "\"assetType\" " + @" = :assetType, + local = :local, temporary = :temporary, creatorid = :creatorid, data = :data + WHERE id=:id; + + INSERT INTO assets + (id, name, description, " + "\"assetType\" " + @", local, + temporary, create_time, access_time, creatorid, asset_flags, data) + Select :id, :name, :description, :assetType, :local, + :temporary, :create_time, :access_time, :creatorid, :asset_flags, :data + Where not EXISTS(SELECT * FROM assets WHERE id=:id) + "; + + string assetName = asset.Name; + if (asset.Name.Length > 64) + { + assetName = asset.Name.Substring(0, 64); + m_log.WarnFormat( + "[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add", + asset.Name, asset.ID, asset.Name.Length, assetName.Length); + } + + string assetDescription = asset.Description; + if (asset.Description.Length > 64) + { + assetDescription = asset.Description.Substring(0, 64); + m_log.WarnFormat( + "[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add", + asset.Description, asset.ID, asset.Description.Length, assetDescription.Length); + } + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) + { + int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000); + command.Parameters.Add(m_database.CreateParameter("id", asset.FullID)); + command.Parameters.Add(m_database.CreateParameter("name", assetName)); + command.Parameters.Add(m_database.CreateParameter("description", assetDescription)); + command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type)); + command.Parameters.Add(m_database.CreateParameter("local", asset.Local)); + command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary)); + command.Parameters.Add(m_database.CreateParameter("access_time", now)); + command.Parameters.Add(m_database.CreateParameter("create_time", now)); + command.Parameters.Add(m_database.CreateParameter("asset_flags", (int)asset.Flags)); + command.Parameters.Add(m_database.CreateParameter("creatorid", asset.Metadata.CreatorID)); + command.Parameters.Add(m_database.CreateParameter("data", asset.Data)); + conn.Open(); + try + { + command.ExecuteNonQuery(); + } + catch(Exception e) + { + m_log.Error("[ASSET DB]: Error storing item :" + e.Message + " sql "+sql); + } + } + } + + +// Commented out since currently unused - this probably should be called in GetAsset() +// private void UpdateAccessTime(AssetBase asset) +// { +// using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = :access_time WHERE id=:id")) +// { +// int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000); +// cmd.Parameters.AddWithValue(":id", asset.FullID.ToString()); +// cmd.Parameters.AddWithValue(":access_time", now); +// try +// { +// cmd.ExecuteNonQuery(); +// } +// catch (Exception e) +// { +// m_log.Error(e.ToString()); +// } +// } +// } + + /// + /// Check if asset exist in m_database + /// + /// + /// true if exist. + override public bool ExistsAsset(UUID uuid) + { + if (GetAsset(uuid) != null) + { + return true; + } + return false; + } + + /// + /// Returns a list of AssetMetadata objects. The list is a subset of + /// the entire data set offset by containing + /// elements. + /// + /// The number of results to discard from the total data set. + /// The number of rows the returned list should contain. + /// A list of AssetMetadata objects. + public override List FetchAssetMetadataSet(int start, int count) + { + List retList = new List(count); + string sql = @" SELECT id, name, description, " + "\"assetType\"" + @", temporary, creatorid + FROM assets + order by id + limit :stop + offset :start;"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("start", start)); + cmd.Parameters.Add(m_database.CreateParameter("stop", start + count - 1)); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + AssetMetadata metadata = new AssetMetadata(); + metadata.FullID = DBGuid.FromDB(reader["id"]); + metadata.Name = (string)reader["name"]; + metadata.Description = (string)reader["description"]; + metadata.Type = Convert.ToSByte(reader["assetType"]); + metadata.Temporary = Convert.ToBoolean(reader["temporary"]); + metadata.CreatorID = (string)reader["creatorid"]; + retList.Add(metadata); + } + } + } + + return retList; + } + + public override bool Delete(string id) + { + return false; + } + #endregion + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLAuthenticationData.cs b/OpenSim/Data/PGSQL/PGSQLAuthenticationData.cs new file mode 100644 index 0000000000..d174112f0f --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLAuthenticationData.cs @@ -0,0 +1,254 @@ +/* + * 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 OpenSimulator 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; +using System.Collections.Generic; +using OpenMetaverse; +using OpenSim.Framework; +using System.Reflection; +using System.Text; +using System.Data; +using Npgsql; +using NpgsqlTypes; + +namespace OpenSim.Data.PGSQL +{ + public class PGSQLAuthenticationData : IAuthenticationData + { + private string m_Realm; + private List m_ColumnNames = null; + private int m_LastExpire = 0; + private string m_ConnectionString; + private PGSQLManager m_database; + + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + + public PGSQLAuthenticationData(string connectionString, string realm) + { + m_Realm = realm; + m_ConnectionString = connectionString; + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + { + conn.Open(); + Migration m = new Migration(conn, GetType().Assembly, "AuthStore"); + m_database = new PGSQLManager(m_ConnectionString); + m.Update(); + } + } + + public AuthenticationData Get(UUID principalID) + { + AuthenticationData ret = new AuthenticationData(); + ret.Data = new Dictionary(); + + string sql = string.Format("select * from {0} where uuid = :principalID", m_Realm); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("principalID", principalID)); + conn.Open(); + using (NpgsqlDataReader result = cmd.ExecuteReader()) + { + if (result.Read()) + { + ret.PrincipalID = principalID; + + if (m_ColumnNames == null) + { + m_ColumnNames = new List(); + + DataTable schemaTable = result.GetSchemaTable(); + foreach (DataRow row in schemaTable.Rows) + m_ColumnNames.Add(row["ColumnName"].ToString()); + } + + foreach (string s in m_ColumnNames) + { + if (s == "UUID"||s == "uuid") + continue; + + ret.Data[s] = result[s].ToString(); + } + return ret; + } + } + } + return null; + } + + public bool Store(AuthenticationData data) + { + if (data.Data.ContainsKey("UUID")) + data.Data.Remove("UUID"); + if (data.Data.ContainsKey("uuid")) + data.Data.Remove("uuid"); + + /* + Dictionary oAuth = new Dictionary(); + + foreach (KeyValuePair oDado in data.Data) + { + if (oDado.Key != oDado.Key.ToLower()) + { + oAuth.Add(oDado.Key.ToLower(), oDado.Value); + } + } + foreach (KeyValuePair oDado in data.Data) + { + if (!oAuth.ContainsKey(oDado.Key.ToLower())) { + oAuth.Add(oDado.Key.ToLower(), oDado.Value); + } + } + */ + string[] fields = new List(data.Data.Keys).ToArray(); + StringBuilder updateBuilder = new StringBuilder(); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + updateBuilder.AppendFormat("update {0} set ", m_Realm); + + bool first = true; + foreach (string field in fields) + { + if (!first) + updateBuilder.Append(", "); + updateBuilder.AppendFormat("\"{0}\" = :{0}",field); + + first = false; + + cmd.Parameters.Add(m_database.CreateParameter("" + field, data.Data[field])); + } + + updateBuilder.Append(" where uuid = :principalID"); + + cmd.CommandText = updateBuilder.ToString(); + cmd.Connection = conn; + cmd.Parameters.Add(m_database.CreateParameter("principalID", data.PrincipalID)); + + conn.Open(); + if (cmd.ExecuteNonQuery() < 1) + { + StringBuilder insertBuilder = new StringBuilder(); + + insertBuilder.AppendFormat("insert into {0} (uuid, \"", m_Realm); + insertBuilder.Append(String.Join("\", \"", fields)); + insertBuilder.Append("\") values (:principalID, :"); + insertBuilder.Append(String.Join(", :", fields)); + insertBuilder.Append(")"); + + cmd.CommandText = insertBuilder.ToString(); + + if (cmd.ExecuteNonQuery() < 1) + { + return false; + } + } + } + return true; + } + + public bool SetDataItem(UUID principalID, string item, string value) + { + string sql = string.Format("update {0} set {1} = :{1} where uuid = :UUID", m_Realm, item); + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("" + item, value)); + conn.Open(); + if (cmd.ExecuteNonQuery() > 0) + return true; + } + return false; + } + + public bool SetToken(UUID principalID, string token, int lifetime) + { + if (System.Environment.TickCount - m_LastExpire > 30000) + DoExpire(); + + string sql = "insert into tokens (uuid, token, validity) values (:principalID, :token, :lifetime)"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("principalID", principalID)); + cmd.Parameters.Add(m_database.CreateParameter("token", token)); + cmd.Parameters.Add(m_database.CreateParameter("lifetime", DateTime.Now.AddMinutes(lifetime))); + conn.Open(); + + if (cmd.ExecuteNonQuery() > 0) + { + return true; + } + } + return false; + } + + public bool CheckToken(UUID principalID, string token, int lifetime) + { + if (System.Environment.TickCount - m_LastExpire > 30000) + DoExpire(); + + DateTime validDate = DateTime.Now.AddMinutes(lifetime); + string sql = "update tokens set validity = :validDate where uuid = :principalID and token = :token and validity > (CURRENT_DATE + CURRENT_TIME)"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("principalID", principalID)); + cmd.Parameters.Add(m_database.CreateParameter("token", token)); + cmd.Parameters.Add(m_database.CreateParameter("validDate", validDate)); + conn.Open(); + + if (cmd.ExecuteNonQuery() > 0) + { + return true; + } + } + return false; + } + + private void DoExpire() + { + DateTime currentDateTime = DateTime.Now; + string sql = "delete from tokens where validity < :currentDateTime"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + conn.Open(); + cmd.Parameters.Add(m_database.CreateParameter("currentDateTime", currentDateTime)); + cmd.ExecuteNonQuery(); + } + m_LastExpire = System.Environment.TickCount; + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLAvatarData.cs b/OpenSim/Data/PGSQL/PGSQLAvatarData.cs new file mode 100644 index 0000000000..d9c49052d4 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLAvatarData.cs @@ -0,0 +1,72 @@ +/* + * 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 OpenSimulator 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.Reflection; +using System.Threading; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using Npgsql; +using NpgsqlTypes; + + +namespace OpenSim.Data.PGSQL +{ + /// + /// A PGSQL Interface for Avatar Storage + /// + public class PGSQLAvatarData : PGSQLGenericTableHandler, + IAvatarData + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public PGSQLAvatarData(string connectionString, string realm) : + base(connectionString, realm, "Avatar") + { + } + + public bool Delete(UUID principalID, string name) + { + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + + cmd.CommandText = String.Format("DELETE FROM {0} where \"PrincipalID\" = :PrincipalID and \"Name\" = :Name", m_Realm); + cmd.Parameters.Add(m_database.CreateParameter("PrincipalID", principalID)); + cmd.Parameters.Add(m_database.CreateParameter("Name", name)); + cmd.Connection = conn; + conn.Open(); + if (cmd.ExecuteNonQuery() > 0) + return true; + + return false; + } + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLEstateData.cs b/OpenSim/Data/PGSQL/PGSQLEstateData.cs new file mode 100644 index 0000000000..347baf3cd1 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLEstateData.cs @@ -0,0 +1,598 @@ +/* + * 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 OpenSimulator 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.Reflection; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using System.Data; +using Npgsql; +using NpgsqlTypes; + +namespace OpenSim.Data.PGSQL +{ + public class PGSQLEstateStore : IEstateDataStore + { + private const string _migrationStore = "EstateStore"; + + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private PGSQLManager _Database; + private string m_connectionString; + private FieldInfo[] _Fields; + private Dictionary _FieldMap = new Dictionary(); + + #region Public methods + + public PGSQLEstateStore() + { + } + + public PGSQLEstateStore(string connectionString) + { + Initialise(connectionString); + } + + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + + /// + /// Initialises the estatedata class. + /// + /// connectionString. + public void Initialise(string connectionString) + { + if (!string.IsNullOrEmpty(connectionString)) + { + m_connectionString = connectionString; + _Database = new PGSQLManager(connectionString); + } + + //Migration settings + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + Migration m = new Migration(conn, GetType().Assembly, "EstateStore"); + m.Update(); + } + + //Interesting way to get parameters! Maybe implement that also with other types + Type t = typeof(EstateSettings); + _Fields = t.GetFields(BindingFlags.NonPublic | + BindingFlags.Instance | + BindingFlags.DeclaredOnly); + + foreach (FieldInfo f in _Fields) + { + if (f.Name.Substring(0, 2) == "m_") + _FieldMap[f.Name.Substring(2)] = f; + } + } + + /// + /// Loads the estate settings. + /// + /// region ID. + /// + public EstateSettings LoadEstateSettings(UUID regionID, bool create) + { + EstateSettings es = new EstateSettings(); + + string sql = "select estate_settings.\"" + String.Join("\",estate_settings.\"", FieldList) + + "\" from estate_map left join estate_settings on estate_map.\"EstateID\" = estate_settings.\"EstateID\" " + + " where estate_settings.\"EstateID\" is not null and \"RegionID\" = :RegionID"; + + bool insertEstate = false; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("RegionID", regionID)); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if (reader.Read()) + { + foreach (string name in FieldList) + { + FieldInfo f = _FieldMap[name]; + object v = reader[name]; + if (f.FieldType == typeof(bool)) + { + f.SetValue(es, v); + } + else if (f.FieldType == typeof(UUID)) + { + UUID estUUID = UUID.Zero; + + UUID.TryParse(v.ToString(), out estUUID); + + f.SetValue(es, estUUID); + } + else if (f.FieldType == typeof(string)) + { + f.SetValue(es, v.ToString()); + } + else if (f.FieldType == typeof(UInt32)) + { + f.SetValue(es, Convert.ToUInt32(v)); + } + else if (f.FieldType == typeof(Single)) + { + f.SetValue(es, Convert.ToSingle(v)); + } + else + f.SetValue(es, v); + } + } + else + { + insertEstate = true; + } + } + } + + if (insertEstate && create) + { + DoCreate(es); + LinkRegion(regionID, (int)es.EstateID); + } + + LoadBanList(es); + + es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); + es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); + es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); + + //Set event + es.OnSave += StoreEstateSettings; + return es; + } + + public EstateSettings CreateNewEstate() + { + EstateSettings es = new EstateSettings(); + es.OnSave += StoreEstateSettings; + + DoCreate(es); + + LoadBanList(es); + + es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); + es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); + es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); + + return es; + } + + private void DoCreate(EstateSettings es) + { + List names = new List(FieldList); + + names.Remove("EstateID"); + + string sql = string.Format("insert into estate_settings (\"{0}\") values ( :{1} )", String.Join("\",\"", names.ToArray()), String.Join(", :", names.ToArray())); + + m_log.Debug("[DB ESTATE]: SQL: " + sql); + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand insertCommand = new NpgsqlCommand(sql, conn)) + { + insertCommand.CommandText = sql + "; Select cast(lastval() as int) as ID ;"; + + foreach (string name in names) + { + insertCommand.Parameters.Add(_Database.CreateParameter("" + name, _FieldMap[name].GetValue(es))); + } + //NpgsqlParameter idParameter = new NpgsqlParameter("ID", SqlDbType.Int); + //idParameter.Direction = ParameterDirection.Output; + //insertCommand.Parameters.Add(idParameter); + conn.Open(); + + es.EstateID = 100; + + using (NpgsqlDataReader result = insertCommand.ExecuteReader()) + { + if (result.Read()) + { + es.EstateID = (uint)result.GetInt32(0); + } + } + + } + + //TODO check if this is needed?? + es.Save(); + } + + /// + /// Stores the estate settings. + /// + /// estate settings + public void StoreEstateSettings(EstateSettings es) + { + List names = new List(FieldList); + + names.Remove("EstateID"); + + string sql = string.Format("UPDATE estate_settings SET "); + foreach (string name in names) + { + sql += "\"" + name + "\" = :" + name + ", "; + } + sql = sql.Remove(sql.LastIndexOf(",")); + sql += " WHERE \"EstateID\" = :EstateID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + foreach (string name in names) + { + cmd.Parameters.Add(_Database.CreateParameter("" + name, _FieldMap[name].GetValue(es))); + } + + cmd.Parameters.Add(_Database.CreateParameter("EstateID", es.EstateID)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + + SaveBanList(es); + SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); + SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); + SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups); + } + + #endregion + + #region Private methods + + private string[] FieldList + { + get { return new List(_FieldMap.Keys).ToArray(); } + } + + private void LoadBanList(EstateSettings es) + { + es.ClearBans(); + + string sql = "select \"bannedUUID\" from estateban where \"EstateID\" = :EstateID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + NpgsqlParameter idParameter = new NpgsqlParameter("EstateID", DbType.Int32); + idParameter.Value = es.EstateID; + cmd.Parameters.Add(idParameter); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + EstateBan eb = new EstateBan(); + + eb.BannedUserID = new UUID((Guid)reader["bannedUUID"]); //uuid; + eb.BannedHostAddress = "0.0.0.0"; + eb.BannedHostIPMask = "0.0.0.0"; + es.AddBan(eb); + } + } + } + } + + private UUID[] LoadUUIDList(uint estateID, string table) + { + List uuids = new List(); + + string sql = string.Format("select uuid from {0} where \"EstateID\" = :EstateID", table); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("EstateID", estateID)); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + uuids.Add(new UUID((Guid)reader["uuid"])); //uuid); + } + } + } + + return uuids.ToArray(); + } + + private void SaveBanList(EstateSettings es) + { + //Delete first + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + using (NpgsqlCommand cmd = conn.CreateCommand()) + { + cmd.CommandText = "delete from estateban where \"EstateID\" = :EstateID"; + cmd.Parameters.AddWithValue("EstateID", (int)es.EstateID); + cmd.ExecuteNonQuery(); + + //Insert after + cmd.CommandText = "insert into estateban (\"EstateID\", \"bannedUUID\",\"bannedIp\", \"bannedIpHostMask\", \"bannedNameMask\") values ( :EstateID, :bannedUUID, '','','' )"; + cmd.Parameters.AddWithValue("bannedUUID", Guid.Empty); + foreach (EstateBan b in es.EstateBans) + { + cmd.Parameters["bannedUUID"].Value = b.BannedUserID.Guid; + cmd.ExecuteNonQuery(); + } + } + } + } + + private void SaveUUIDList(uint estateID, string table, UUID[] data) + { + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + using (NpgsqlCommand cmd = conn.CreateCommand()) + { + cmd.Parameters.AddWithValue("EstateID", (int)estateID); + cmd.CommandText = string.Format("delete from {0} where \"EstateID\" = :EstateID", table); + cmd.ExecuteNonQuery(); + + cmd.CommandText = string.Format("insert into {0} (\"EstateID\", uuid) values ( :EstateID, :uuid )", table); + cmd.Parameters.AddWithValue("uuid", Guid.Empty); + foreach (UUID uuid in data) + { + cmd.Parameters["uuid"].Value = uuid.Guid; //.ToString(); //TODO check if this works + cmd.ExecuteNonQuery(); + } + } + } + } + + public EstateSettings LoadEstateSettings(int estateID) + { + EstateSettings es = new EstateSettings(); + string sql = "select estate_settings.\"" + String.Join("\",estate_settings.\"", FieldList) + "\" from estate_settings where \"EstateID\" = :EstateID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.AddWithValue("EstateID", (int)estateID); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if (reader.Read()) + { + foreach (string name in FieldList) + { + FieldInfo f = _FieldMap[name]; + object v = reader[name]; + if (f.FieldType == typeof(bool)) + { + f.SetValue(es, Convert.ToInt32(v) != 0); + } + else if (f.FieldType == typeof(UUID)) + { + f.SetValue(es, new UUID((Guid)v)); // uuid); + } + else if (f.FieldType == typeof(string)) + { + f.SetValue(es, v.ToString()); + } + else if (f.FieldType == typeof(UInt32)) + { + f.SetValue(es, Convert.ToUInt32(v)); + } + else if (f.FieldType == typeof(Single)) + { + f.SetValue(es, Convert.ToSingle(v)); + } + else + f.SetValue(es, v); + } + } + + } + } + } + LoadBanList(es); + + es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); + es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); + es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); + + //Set event + es.OnSave += StoreEstateSettings; + return es; + + } + + public List LoadEstateSettingsAll() + { + List allEstateSettings = new List(); + + List allEstateIds = GetEstatesAll(); + + foreach (int estateId in allEstateIds) + allEstateSettings.Add(LoadEstateSettings(estateId)); + + return allEstateSettings; + } + + public List GetEstates(string search) + { + List result = new List(); + string sql = "select \"estateID\" from estate_settings where lower(\"EstateName\") = lower(:EstateName)"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.AddWithValue("EstateName", search); + + using (IDataReader reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(Convert.ToInt32(reader["EstateID"])); + } + reader.Close(); + } + } + } + + return result; + } + + public List GetEstatesAll() + { + List result = new List(); + string sql = "select \"EstateID\" from estate_settings"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + using (IDataReader reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(Convert.ToInt32(reader["EstateID"])); + } + reader.Close(); + } + } + } + + return result; + } + + public List GetEstatesByOwner(UUID ownerID) + { + List result = new List(); + string sql = "select \"estateID\" from estate_settings where \"EstateOwner\" = :EstateOwner"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.AddWithValue("EstateOwner", ownerID); + + using (IDataReader reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(Convert.ToInt32(reader["EstateID"])); + } + reader.Close(); + } + } + } + + return result; + } + + public bool LinkRegion(UUID regionID, int estateID) + { + string deleteSQL = "delete from estate_map where \"RegionID\" = :RegionID"; + string insertSQL = "insert into estate_map values (:RegionID, :EstateID)"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + + NpgsqlTransaction transaction = conn.BeginTransaction(); + + try + { + using (NpgsqlCommand cmd = new NpgsqlCommand(deleteSQL, conn)) + { + cmd.Transaction = transaction; + cmd.Parameters.AddWithValue("RegionID", regionID.Guid); + + cmd.ExecuteNonQuery(); + } + + using (NpgsqlCommand cmd = new NpgsqlCommand(insertSQL, conn)) + { + cmd.Transaction = transaction; + cmd.Parameters.AddWithValue("RegionID", regionID.Guid); + cmd.Parameters.AddWithValue("EstateID", estateID); + + int ret = cmd.ExecuteNonQuery(); + + if (ret != 0) + transaction.Commit(); + else + transaction.Rollback(); + + return (ret != 0); + } + } + catch (Exception ex) + { + m_log.Error("[REGION DB]: LinkRegion failed: " + ex.Message); + transaction.Rollback(); + } + } + return false; + } + + public List GetRegions(int estateID) + { + List result = new List(); + string sql = "select \"RegionID\" from estate_map where \"EstateID\" = :EstateID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.AddWithValue("EstateID", estateID); + + using (IDataReader reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(DBGuid.FromDB(reader["RegionID"])); + } + reader.Close(); + } + } + } + + return result; + } + + public bool DeleteEstate(int estateID) + { + // TODO: Implementation! + return false; + } + #endregion + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLFramework.cs b/OpenSim/Data/PGSQL/PGSQLFramework.cs new file mode 100644 index 0000000000..494b0aad8f --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLFramework.cs @@ -0,0 +1,82 @@ +/* + * 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 OpenSimulator 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; +using System.Collections.Generic; +using System.Data; +using OpenMetaverse; +using OpenSim.Framework; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + /// + /// A database interface class to a user profile storage system + /// + public class PGSqlFramework + { + private static readonly log4net.ILog m_log = + log4net.LogManager.GetLogger( + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + protected string m_connectionString; + protected object m_dbLock = new object(); + + protected PGSqlFramework(string connectionString) + { + m_connectionString = connectionString; + } + + ////////////////////////////////////////////////////////////// + // + // All non queries are funneled through one connection + // to increase performance a little + // + protected int ExecuteNonQuery(NpgsqlCommand cmd) + { + lock (m_dbLock) + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) + { + dbcon.Open(); + cmd.Connection = dbcon; + + try + { + return cmd.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.Error(e.Message, e); + return 0; + } + } + } + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLFriendsData.cs b/OpenSim/Data/PGSQL/PGSQLFriendsData.cs new file mode 100644 index 0000000000..4c1ee02e41 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLFriendsData.cs @@ -0,0 +1,116 @@ +/* + * 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 OpenSimulator 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; +using System.Collections.Generic; +using System.Data; +using OpenMetaverse; +using OpenSim.Framework; +using System.Reflection; +using System.Text; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + public class PGSQLFriendsData : PGSQLGenericTableHandler, IFriendsData + { + public PGSQLFriendsData(string connectionString, string realm) + : base(connectionString, realm, "FriendsStore") + { + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + { + conn.Open(); + Migration m = new Migration(conn, GetType().Assembly, "FriendsStore"); + m.Update(); + } + } + + + public bool Delete(string principalID, string friend) + { + UUID princUUID = UUID.Zero; + + bool ret = UUID.TryParse(principalID, out princUUID); + + if (ret) + return Delete(princUUID, friend); + else + return false; + } + + public bool Delete(UUID principalID, string friend) + { + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + cmd.CommandText = String.Format("delete from {0} where \"PrincipalID\" = :PrincipalID and \"Friend\" = :Friend", m_Realm); + cmd.Parameters.Add(m_database.CreateParameter("PrincipalID", principalID.ToString())); + cmd.Parameters.Add(m_database.CreateParameter("Friend", friend)); + cmd.Connection = conn; + conn.Open(); + cmd.ExecuteNonQuery(); + + return true; + } + } + + public FriendsData[] GetFriends(string principalID) + { + UUID princUUID = UUID.Zero; + + bool ret = UUID.TryParse(principalID, out princUUID); + + if (ret) + return GetFriends(princUUID); + else + return new FriendsData[0]; + } + + public FriendsData[] GetFriends(UUID principalID) + { + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + + cmd.CommandText = String.Format("select a.*,case when b.\"Flags\" is null then '-1' else b.\"Flags\" end as \"TheirFlags\" from {0} as a " + + " left join {0} as b on a.\"PrincipalID\" = b.\"Friend\" and a.\"Friend\" = b.\"PrincipalID\" " + + " where a.\"PrincipalID\" = :PrincipalID", m_Realm); + cmd.Parameters.Add(m_database.CreateParameter("PrincipalID", principalID.ToString())); + cmd.Connection = conn; + conn.Open(); + return DoQuery(cmd); + } + } + + public FriendsData[] GetFriends(Guid principalID) + { + return GetFriends(principalID); + } + + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLGenericTableHandler.cs b/OpenSim/Data/PGSQL/PGSQLGenericTableHandler.cs new file mode 100644 index 0000000000..2151568a01 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLGenericTableHandler.cs @@ -0,0 +1,519 @@ +/* + * 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 OpenSimulator 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.Reflection; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using System.Text; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + public class PGSQLGenericTableHandler : PGSqlFramework where T : class, new() + { + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected string m_ConnectionString; + protected PGSQLManager m_database; //used for parameter type translation + protected Dictionary m_Fields = + new Dictionary(); + + protected Dictionary m_FieldTypes = new Dictionary(); + + protected List m_ColumnNames = null; + protected string m_Realm; + protected FieldInfo m_DataField = null; + + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + + public PGSQLGenericTableHandler(string connectionString, + string realm, string storeName) + : base(connectionString) + { + m_Realm = realm; + + m_ConnectionString = connectionString; + + if (storeName != String.Empty) + { + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + { + conn.Open(); + Migration m = new Migration(conn, GetType().Assembly, storeName); + m.Update(); + } + + } + m_database = new PGSQLManager(m_ConnectionString); + + Type t = typeof(T); + FieldInfo[] fields = t.GetFields(BindingFlags.Public | + BindingFlags.Instance | + BindingFlags.DeclaredOnly); + + LoadFieldTypes(); + + if (fields.Length == 0) + return; + + foreach (FieldInfo f in fields) + { + if (f.Name != "Data") + m_Fields[f.Name] = f; + else + m_DataField = f; + } + + } + + private void LoadFieldTypes() + { + m_FieldTypes = new Dictionary(); + + string query = string.Format(@"select column_name,data_type + from INFORMATION_SCHEMA.COLUMNS + where table_name = lower('{0}'); + + ", m_Realm); + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) + { + conn.Open(); + using (NpgsqlDataReader rdr = cmd.ExecuteReader()) + { + while (rdr.Read()) + { + // query produces 0 to many rows of single column, so always add the first item in each row + m_FieldTypes.Add((string)rdr[0], (string)rdr[1]); + } + } + } + } + + private void CheckColumnNames(NpgsqlDataReader reader) + { + if (m_ColumnNames != null) + return; + + m_ColumnNames = new List(); + + DataTable schemaTable = reader.GetSchemaTable(); + + foreach (DataRow row in schemaTable.Rows) + { + if (row["ColumnName"] != null && + (!m_Fields.ContainsKey(row["ColumnName"].ToString()))) + m_ColumnNames.Add(row["ColumnName"].ToString()); + + } + } + + // TODO GET CONSTRAINTS FROM POSTGRESQL + private List GetConstraints() + { + List constraints = new List(); + string query = string.Format(@"SELECT kcu.column_name + FROM information_schema.table_constraints tc + LEFT JOIN information_schema.key_column_usage kcu + ON tc.constraint_catalog = kcu.constraint_catalog + AND tc.constraint_schema = kcu.constraint_schema + AND tc.constraint_name = kcu.constraint_name + + LEFT JOIN information_schema.referential_constraints rc + ON tc.constraint_catalog = rc.constraint_catalog + AND tc.constraint_schema = rc.constraint_schema + AND tc.constraint_name = rc.constraint_name + + LEFT JOIN information_schema.constraint_column_usage ccu + ON rc.unique_constraint_catalog = ccu.constraint_catalog + AND rc.unique_constraint_schema = ccu.constraint_schema + AND rc.unique_constraint_name = ccu.constraint_name + + where tc.table_name = lower('{0}') + and lower(tc.constraint_type) in ('primary key') + and kcu.column_name is not null + ;", m_Realm); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) + { + conn.Open(); + using (NpgsqlDataReader rdr = cmd.ExecuteReader()) + { + while (rdr.Read()) + { + // query produces 0 to many rows of single column, so always add the first item in each row + constraints.Add((string)rdr[0]); + } + } + return constraints; + } + } + + public virtual T[] Get(string field, string key) + { + return Get(new string[] { field }, new string[] { key }); + } + + public virtual T[] Get(string[] fields, string[] keys) + { + if (fields.Length != keys.Length) + return new T[0]; + + List terms = new List(); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + + for (int i = 0; i < fields.Length; i++) + { + if ( m_FieldTypes.ContainsKey(fields[i]) ) + cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]])); + else + cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i])); + + terms.Add(" \"" + fields[i] + "\" = :" + fields[i]); + } + + string where = String.Join(" AND ", terms.ToArray()); + + string query = String.Format("SELECT * FROM {0} WHERE {1}", + m_Realm, where); + + cmd.Connection = conn; + cmd.CommandText = query; + conn.Open(); + return DoQuery(cmd); + } + } + + protected T[] DoQuery(NpgsqlCommand cmd) + { + List result = new List(); + if (cmd.Connection == null) + { + cmd.Connection = new NpgsqlConnection(m_connectionString); + } + if (cmd.Connection.State == ConnectionState.Closed) + { + cmd.Connection.Open(); + } + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if (reader == null) + return new T[0]; + + CheckColumnNames(reader); + + while (reader.Read()) + { + T row = new T(); + + foreach (string name in m_Fields.Keys) + { + if (m_Fields[name].GetValue(row) is bool) + { + int v = Convert.ToInt32(reader[name]); + m_Fields[name].SetValue(row, v != 0 ? true : false); + } + else if (m_Fields[name].GetValue(row) is UUID) + { + UUID uuid = UUID.Zero; + + UUID.TryParse(reader[name].ToString(), out uuid); + m_Fields[name].SetValue(row, uuid); + } + else if (m_Fields[name].GetValue(row) is int) + { + int v = Convert.ToInt32(reader[name]); + m_Fields[name].SetValue(row, v); + } + else + { + m_Fields[name].SetValue(row, reader[name]); + } + } + + if (m_DataField != null) + { + Dictionary data = + new Dictionary(); + + foreach (string col in m_ColumnNames) + { + data[col] = reader[col].ToString(); + + if (data[col] == null) + data[col] = String.Empty; + } + + m_DataField.SetValue(row, data); + } + + result.Add(row); + } + return result.ToArray(); + } + } + + public virtual T[] Get(string where) + { + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + + string query = String.Format("SELECT * FROM {0} WHERE {1}", + m_Realm, where); + cmd.Connection = conn; + cmd.CommandText = query; + + //m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where); + + conn.Open(); + return DoQuery(cmd); + } + } + + public virtual bool Store(T row) + { + List constraintFields = GetConstraints(); + List> constraints = new List>(); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + + StringBuilder query = new StringBuilder(); + List names = new List(); + List values = new List(); + + foreach (FieldInfo fi in m_Fields.Values) + { + names.Add(fi.Name); + values.Add(":" + fi.Name); + // Temporarily return more information about what field is unexpectedly null for + // http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the + // InventoryTransferModule or we may be required to substitute a DBNull here. + if (fi.GetValue(row) == null) + throw new NullReferenceException( + string.Format( + "[PGSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null", + fi.Name, row)); + + if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name)) + { + constraints.Add(new KeyValuePair(fi.Name, fi.GetValue(row).ToString() )); + } + if (m_FieldTypes.ContainsKey(fi.Name)) + cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row), m_FieldTypes[fi.Name])); + else + cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row))); + } + + if (m_DataField != null) + { + Dictionary data = + (Dictionary)m_DataField.GetValue(row); + + foreach (KeyValuePair kvp in data) + { + if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key)) + { + constraints.Add(new KeyValuePair(kvp.Key, kvp.Key)); + } + names.Add(kvp.Key); + values.Add(":" + kvp.Key); + + if (m_FieldTypes.ContainsKey(kvp.Key)) + cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value, m_FieldTypes[kvp.Key])); + else + cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value)); + } + + } + + query.AppendFormat("UPDATE {0} SET ", m_Realm); + int i = 0; + for (i = 0; i < names.Count - 1; i++) + { + query.AppendFormat("\"{0}\" = {1}, ", names[i], values[i]); + } + query.AppendFormat("\"{0}\" = {1} ", names[i], values[i]); + if (constraints.Count > 0) + { + List terms = new List(); + for (int j = 0; j < constraints.Count; j++) + { + terms.Add(String.Format(" \"{0}\" = :{0}", constraints[j].Key)); + } + string where = String.Join(" AND ", terms.ToArray()); + query.AppendFormat(" WHERE {0} ", where); + + } + cmd.Connection = conn; + cmd.CommandText = query.ToString(); + + conn.Open(); + if (cmd.ExecuteNonQuery() > 0) + { + //m_log.WarnFormat("[PGSQLGenericTable]: Updating {0}", m_Realm); + return true; + } + else + { + // assume record has not yet been inserted + + query = new StringBuilder(); + query.AppendFormat("INSERT INTO {0} (\"", m_Realm); + query.Append(String.Join("\",\"", names.ToArray())); + query.Append("\") values (" + String.Join(",", values.ToArray()) + ")"); + cmd.Connection = conn; + cmd.CommandText = query.ToString(); + + // m_log.WarnFormat("[PGSQLGenericTable]: Inserting into {0} sql {1}", m_Realm, cmd.CommandText); + + if (conn.State != ConnectionState.Open) + conn.Open(); + if (cmd.ExecuteNonQuery() > 0) + return true; + } + + return false; + } + } + + public virtual bool Delete(string field, string key) + { + return Delete(new string[] { field }, new string[] { key }); + } + + public virtual bool Delete(string[] fields, string[] keys) + { + if (fields.Length != keys.Length) + return false; + + List terms = new List(); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + for (int i = 0; i < fields.Length; i++) + { + if (m_FieldTypes.ContainsKey(fields[i])) + cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]])); + else + cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i])); + + terms.Add(" \"" + fields[i] + "\" = :" + fields[i]); + } + + string where = String.Join(" AND ", terms.ToArray()); + + string query = String.Format("DELETE FROM {0} WHERE {1}", m_Realm, where); + + cmd.Connection = conn; + cmd.CommandText = query; + conn.Open(); + + if (cmd.ExecuteNonQuery() > 0) + { + //m_log.Warn("[PGSQLGenericTable]: " + deleteCommand); + return true; + } + return false; + } + } + public long GetCount(string field, string key) + { + return GetCount(new string[] { field }, new string[] { key }); + } + + public long GetCount(string[] fields, string[] keys) + { + if (fields.Length != keys.Length) + return 0; + + List terms = new List(); + + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + for (int i = 0; i < fields.Length; i++) + { + cmd.Parameters.AddWithValue(fields[i], keys[i]); + terms.Add("\"" + fields[i] + "\" = :" + fields[i]); + } + + string where = String.Join(" and ", terms.ToArray()); + + string query = String.Format("select count(*) from {0} where {1}", + m_Realm, where); + + cmd.CommandText = query; + + Object result = DoQueryScalar(cmd); + + return Convert.ToInt64(result); + } + } + + public long GetCount(string where) + { + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + string query = String.Format("select count(*) from {0} where {1}", + m_Realm, where); + + cmd.CommandText = query; + + object result = DoQueryScalar(cmd); + + return Convert.ToInt64(result); + } + } + + public object DoQueryScalar(NpgsqlCommand cmd) + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(m_ConnectionString)) + { + dbcon.Open(); + cmd.Connection = dbcon; + + return cmd.ExecuteScalar(); + } + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLGridUserData.cs b/OpenSim/Data/PGSQL/PGSQLGridUserData.cs new file mode 100644 index 0000000000..89319f3a58 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLGridUserData.cs @@ -0,0 +1,68 @@ +/* + * 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 OpenSimulator 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.Reflection; +using System.Threading; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; + +namespace OpenSim.Data.PGSQL +{ + /// + /// A PGSQL Interface for Avatar Storage + /// + public class PGSQLGridUserData : PGSQLGenericTableHandler, + IGridUserData + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public PGSQLGridUserData(string connectionString, string realm) : + base(connectionString, realm, "GridUserStore") + { + } + + public new GridUserData Get(string userID) + { + GridUserData[] ret = Get("UserID", userID); + + if (ret.Length == 0) + return null; + + return ret[0]; + } + + public GridUserData[] GetAll(string userID) + { + return base.Get(String.Format("\"UserID\" LIKE '{0}%'", userID)); + } + + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLGroupsData.cs b/OpenSim/Data/PGSQL/PGSQLGroupsData.cs new file mode 100644 index 0000000000..ed75b638a9 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLGroupsData.cs @@ -0,0 +1,481 @@ +/* + * 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 OpenSimulator 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; +using System.Collections.Generic; +using System.Reflection; +using OpenSim.Framework; +using OpenMetaverse; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + public class PGSQLGroupsData : IGroupsData + { + private PGSqlGroupsGroupsHandler m_Groups; + private PGSqlGroupsMembershipHandler m_Membership; + private PGSqlGroupsRolesHandler m_Roles; + private PGSqlGroupsRoleMembershipHandler m_RoleMembership; + private PGSqlGroupsInvitesHandler m_Invites; + private PGSqlGroupsNoticesHandler m_Notices; + private PGSqlGroupsPrincipalsHandler m_Principals; + + public PGSQLGroupsData(string connectionString, string realm) + { + m_Groups = new PGSqlGroupsGroupsHandler(connectionString, realm + "_groups", realm + "_Store"); + m_Membership = new PGSqlGroupsMembershipHandler(connectionString, realm + "_membership"); + m_Roles = new PGSqlGroupsRolesHandler(connectionString, realm + "_roles"); + m_RoleMembership = new PGSqlGroupsRoleMembershipHandler(connectionString, realm + "_rolemembership"); + m_Invites = new PGSqlGroupsInvitesHandler(connectionString, realm + "_invites"); + m_Notices = new PGSqlGroupsNoticesHandler(connectionString, realm + "_notices"); + m_Principals = new PGSqlGroupsPrincipalsHandler(connectionString, realm + "_principals"); + } + + #region groups table + public bool StoreGroup(GroupData data) + { + return m_Groups.Store(data); + } + + public GroupData RetrieveGroup(UUID groupID) + { + GroupData[] groups = m_Groups.Get("GroupID", groupID.ToString()); + if (groups.Length > 0) + return groups[0]; + + return null; + } + + public GroupData RetrieveGroup(string name) + { + GroupData[] groups = m_Groups.Get("Name", name); + if (groups.Length > 0) + return groups[0]; + + return null; + } + + public GroupData[] RetrieveGroups(string pattern) + { + if (string.IsNullOrEmpty(pattern)) // True for where clause + pattern = " true ORDER BY lower(\"Name\") LIMIT 100"; + else + pattern = string.Format(" lower(\"Name\") LIKE lower('%{0}%') ORDER BY lower(\"Name\") LIMIT 100", pattern); + + return m_Groups.Get(pattern); + } + + public bool DeleteGroup(UUID groupID) + { + return m_Groups.Delete("GroupID", groupID.ToString()); + } + + public int GroupsCount() + { + return (int)m_Groups.GetCount(" \"Location\" = \"\""); + } + + #endregion + + #region membership table + public MembershipData[] RetrieveMembers(UUID groupID) + { + return m_Membership.Get("GroupID", groupID.ToString()); + } + + public MembershipData RetrieveMember(UUID groupID, string pricipalID) + { + MembershipData[] m = m_Membership.Get(new string[] { "GroupID", "PrincipalID" }, + new string[] { groupID.ToString(), pricipalID }); + if (m != null && m.Length > 0) + return m[0]; + + return null; + } + + public MembershipData[] RetrieveMemberships(string pricipalID) + { + return m_Membership.Get("PrincipalID", pricipalID.ToString()); + } + + public bool StoreMember(MembershipData data) + { + return m_Membership.Store(data); + } + + public bool DeleteMember(UUID groupID, string pricipalID) + { + return m_Membership.Delete(new string[] { "GroupID", "PrincipalID" }, + new string[] { groupID.ToString(), pricipalID }); + } + + public int MemberCount(UUID groupID) + { + return (int)m_Membership.GetCount("GroupID", groupID.ToString()); + } + #endregion + + #region roles table + public bool StoreRole(RoleData data) + { + return m_Roles.Store(data); + } + + public RoleData RetrieveRole(UUID groupID, UUID roleID) + { + RoleData[] data = m_Roles.Get(new string[] { "GroupID", "RoleID" }, + new string[] { groupID.ToString(), roleID.ToString() }); + + if (data != null && data.Length > 0) + return data[0]; + + return null; + } + + public RoleData[] RetrieveRoles(UUID groupID) + { + //return m_Roles.RetrieveRoles(groupID); + return m_Roles.Get("GroupID", groupID.ToString()); + } + + public bool DeleteRole(UUID groupID, UUID roleID) + { + return m_Roles.Delete(new string[] { "GroupID", "RoleID" }, + new string[] { groupID.ToString(), roleID.ToString() }); + } + + public int RoleCount(UUID groupID) + { + return (int)m_Roles.GetCount("GroupID", groupID.ToString()); + } + + + #endregion + + #region rolememberhip table + public RoleMembershipData[] RetrieveRolesMembers(UUID groupID) + { + RoleMembershipData[] data = m_RoleMembership.Get("GroupID", groupID.ToString()); + + return data; + } + + public RoleMembershipData[] RetrieveRoleMembers(UUID groupID, UUID roleID) + { + RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID" }, + new string[] { groupID.ToString(), roleID.ToString() }); + + return data; + } + + public RoleMembershipData[] RetrieveMemberRoles(UUID groupID, string principalID) + { + RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "PrincipalID" }, + new string[] { groupID.ToString(), principalID.ToString() }); + + return data; + } + + public RoleMembershipData RetrieveRoleMember(UUID groupID, UUID roleID, string principalID) + { + RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID", "PrincipalID" }, + new string[] { groupID.ToString(), roleID.ToString(), principalID.ToString() }); + + if (data != null && data.Length > 0) + return data[0]; + + return null; + } + + public int RoleMemberCount(UUID groupID, UUID roleID) + { + return (int)m_RoleMembership.GetCount(new string[] { "GroupID", "RoleID" }, + new string[] { groupID.ToString(), roleID.ToString() }); + } + + public bool StoreRoleMember(RoleMembershipData data) + { + return m_RoleMembership.Store(data); + } + + public bool DeleteRoleMember(RoleMembershipData data) + { + return m_RoleMembership.Delete(new string[] { "GroupID", "RoleID", "PrincipalID"}, + new string[] { data.GroupID.ToString(), data.RoleID.ToString(), data.PrincipalID }); + } + + public bool DeleteMemberAllRoles(UUID groupID, string principalID) + { + return m_RoleMembership.Delete(new string[] { "GroupID", "PrincipalID" }, + new string[] { groupID.ToString(), principalID }); + } + + #endregion + + #region principals table + public bool StorePrincipal(PrincipalData data) + { + return m_Principals.Store(data); + } + + public PrincipalData RetrievePrincipal(string principalID) + { + PrincipalData[] p = m_Principals.Get("PrincipalID", principalID); + if (p != null && p.Length > 0) + return p[0]; + + return null; + } + + public bool DeletePrincipal(string principalID) + { + return m_Principals.Delete("PrincipalID", principalID); + } + #endregion + + #region invites table + + public bool StoreInvitation(InvitationData data) + { + return m_Invites.Store(data); + } + + public InvitationData RetrieveInvitation(UUID inviteID) + { + InvitationData[] invites = m_Invites.Get("InviteID", inviteID.ToString()); + + if (invites != null && invites.Length > 0) + return invites[0]; + + return null; + } + + public InvitationData RetrieveInvitation(UUID groupID, string principalID) + { + InvitationData[] invites = m_Invites.Get(new string[] { "GroupID", "PrincipalID" }, + new string[] { groupID.ToString(), principalID }); + + if (invites != null && invites.Length > 0) + return invites[0]; + + return null; + } + + public bool DeleteInvite(UUID inviteID) + { + return m_Invites.Delete("InviteID", inviteID.ToString()); + } + + public void DeleteOldInvites() + { + m_Invites.DeleteOld(); + } + + #endregion + + #region notices table + + public bool StoreNotice(NoticeData data) + { + return m_Notices.Store(data); + } + + public NoticeData RetrieveNotice(UUID noticeID) + { + NoticeData[] notices = m_Notices.Get("NoticeID", noticeID.ToString()); + + if (notices != null && notices.Length > 0) + return notices[0]; + + return null; + } + + public NoticeData[] RetrieveNotices(UUID groupID) + { + NoticeData[] notices = m_Notices.Get("GroupID", groupID.ToString()); + + return notices; + } + + public bool DeleteNotice(UUID noticeID) + { + return m_Notices.Delete("NoticeID", noticeID.ToString()); + } + + public void DeleteOldNotices() + { + m_Notices.DeleteOld(); + } + + #endregion + + #region combinations + public MembershipData RetrievePrincipalGroupMembership(string principalID, UUID groupID) + { + // TODO + return null; + } + public MembershipData[] RetrievePrincipalGroupMemberships(string principalID) + { + // TODO + return null; + } + + #endregion + } + + public class PGSqlGroupsGroupsHandler : PGSQLGenericTableHandler + { + protected override Assembly Assembly + { + // WARNING! Moving migrations to this assembly!!! + get { return GetType().Assembly; } + } + + public PGSqlGroupsGroupsHandler(string connectionString, string realm, string store) + : base(connectionString, realm, store) + { + } + + } + + public class PGSqlGroupsMembershipHandler : PGSQLGenericTableHandler + { + protected override Assembly Assembly + { + // WARNING! Moving migrations to this assembly!!! + get { return GetType().Assembly; } + } + + public PGSqlGroupsMembershipHandler(string connectionString, string realm) + : base(connectionString, realm, string.Empty) + { + } + + } + + public class PGSqlGroupsRolesHandler : PGSQLGenericTableHandler + { + protected override Assembly Assembly + { + // WARNING! Moving migrations to this assembly!!! + get { return GetType().Assembly; } + } + + public PGSqlGroupsRolesHandler(string connectionString, string realm) + : base(connectionString, realm, string.Empty) + { + } + + } + + public class PGSqlGroupsRoleMembershipHandler : PGSQLGenericTableHandler + { + protected override Assembly Assembly + { + // WARNING! Moving migrations to this assembly!!! + get { return GetType().Assembly; } + } + + public PGSqlGroupsRoleMembershipHandler(string connectionString, string realm) + : base(connectionString, realm, string.Empty) + { + } + + } + + public class PGSqlGroupsInvitesHandler : PGSQLGenericTableHandler + { + protected override Assembly Assembly + { + // WARNING! Moving migrations to this assembly!!! + get { return GetType().Assembly; } + } + + public PGSqlGroupsInvitesHandler(string connectionString, string realm) + : base(connectionString, realm, string.Empty) + { + } + + public void DeleteOld() + { + uint now = (uint)Util.UnixTimeSinceEpoch(); + + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + cmd.CommandText = String.Format("delete from {0} where \"TMStamp\" < :tstamp", m_Realm); + cmd.Parameters.AddWithValue("tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old + + ExecuteNonQuery(cmd); + } + + } + } + + public class PGSqlGroupsNoticesHandler : PGSQLGenericTableHandler + { + protected override Assembly Assembly + { + // WARNING! Moving migrations to this assembly!!! + get { return GetType().Assembly; } + } + + public PGSqlGroupsNoticesHandler(string connectionString, string realm) + : base(connectionString, realm, string.Empty) + { + } + + public void DeleteOld() + { + uint now = (uint)Util.UnixTimeSinceEpoch(); + + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + cmd.CommandText = String.Format("delete from {0} where \"TMStamp\" < :tstamp", m_Realm); + cmd.Parameters.AddWithValue("tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old + + ExecuteNonQuery(cmd); + } + + } + } + + public class PGSqlGroupsPrincipalsHandler : PGSQLGenericTableHandler + { + protected override Assembly Assembly + { + // WARNING! Moving migrations to this assembly!!! + get { return GetType().Assembly; } + } + + public PGSqlGroupsPrincipalsHandler(string connectionString, string realm) + : base(connectionString, realm, string.Empty) + { + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLHGTravelData.cs b/OpenSim/Data/PGSQL/PGSQLHGTravelData.cs new file mode 100644 index 0000000000..c71b15f474 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLHGTravelData.cs @@ -0,0 +1,80 @@ +/* + * 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 OpenSimulator 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.Reflection; +using System.Threading; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + /// + /// A PGSQL Interface for user grid data + /// + public class PGSQLHGTravelData : PGSQLGenericTableHandler, IHGTravelingData + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public PGSQLHGTravelData(string connectionString, string realm) : base(connectionString, realm, "HGTravelStore") { } + + public HGTravelingData Get(UUID sessionID) + { + HGTravelingData[] ret = Get("SessionID", sessionID.ToString()); + + if (ret.Length == 0) + return null; + + return ret[0]; + } + + public HGTravelingData[] GetSessions(UUID userID) + { + return base.Get("UserID", userID.ToString()); + } + + public bool Delete(UUID sessionID) + { + return Delete("SessionID", sessionID.ToString()); + } + + public void DeleteOld() + { + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + cmd.CommandText = String.Format(@"delete from {0} where ""TMStamp"" < CURRENT_DATE - INTERVAL '2 day'", m_Realm); + + ExecuteNonQuery(cmd); + } + + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLInventoryData.cs b/OpenSim/Data/PGSQL/PGSQLInventoryData.cs new file mode 100644 index 0000000000..c9994332fa --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLInventoryData.cs @@ -0,0 +1,831 @@ +/* + * 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 OpenSimulator 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.Reflection; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + /// + /// A PGSQL interface for the inventory server + /// + public class PGSQLInventoryData : IInventoryDataPlugin + { + private const string _migrationStore = "InventoryStore"; + + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// The database manager + /// + private PGSQLManager database; + private string m_connectionString; + + #region IPlugin members + + [Obsolete("Cannot be default-initialized!")] + public void Initialise() + { + m_log.Info("[PGSQLInventoryData]: " + Name + " cannot be default-initialized!"); + throw new PluginNotInitialisedException(Name); + } + + /// + /// Loads and initialises the PGSQL inventory storage interface + /// + /// connect string + /// use PGSQL_connection.ini + public void Initialise(string connectionString) + { + m_connectionString = connectionString; + database = new PGSQLManager(connectionString); + + //New migrations check of store + database.CheckMigration(_migrationStore); + } + + /// + /// The name of this DB provider + /// + /// A string containing the name of the DB provider + public string Name + { + get { return "PGSQL Inventory Data Interface"; } + } + + /// + /// Closes this DB provider + /// + public void Dispose() + { + database = null; + } + + /// + /// Returns the version of this DB provider + /// + /// A string containing the DB provider + public string Version + { + get { return database.getVersion(); } + } + + #endregion + + #region Folder methods + + /// + /// 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(UUID user) + { + if (user == UUID.Zero) + return new List(); + + return getInventoryFolders(UUID.Zero, user); + } + + /// + /// see InventoryItemBase.getUserRootFolder + /// + /// the User UUID + /// + public InventoryFolderBase getUserRootFolder(UUID user) + { + List items = getUserRootFolders(user); + + 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]; + } + + return rootFolder; + } + + /// + /// 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(UUID parentID) + { + return getInventoryFolders(parentID, UUID.Zero); + } + + /// + /// Returns a specified inventory folder + /// + /// The folder to return + /// A folder class + public InventoryFolderBase getInventoryFolder(UUID folderID) + { + string sql = "SELECT * FROM inventoryfolders WHERE \"folderID\" = :folderID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(database.CreateParameter("folderID", folderID)); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if (reader.Read()) + { + return readInventoryFolder(reader); + } + } + } + m_log.InfoFormat("[INVENTORY DB] : Found no inventory folder with ID : {0}", folderID); + return null; + } + + /// + /// Returns all child folders in the hierarchy from the parent folder and down. + /// Does not return the parent folder itself. + /// + /// The folder to get subfolders for + /// A list of inventory folders + public List getFolderHierarchy(UUID parentID) + { + //Note maybe change this to use a Dataset that loading in all folders of a user and then go throw it that way. + //Note this is changed so it opens only one connection to the database and not everytime it wants to get data. + + /* NOTE: the implementation below is very inefficient (makes a separate request to get subfolders for + * every found folder, recursively). Inventory code for other DBs has been already rewritten to get ALL + * inventory for a specific user at once. + * + * Meanwhile, one little thing is corrected: getFolderHierarchy(UUID.Zero) doesn't make sense and should never + * be used, so check for that and return an empty list. + */ + + List folders = new List(); + + if (parentID == UUID.Zero) + return folders; + + string sql = "SELECT * FROM inventoryfolders WHERE \"parentFolderID\" = :parentID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(database.CreateParameter("parentID", parentID)); + conn.Open(); + folders.AddRange(getInventoryFolders(cmd)); + + List tempFolders = new List(); + + foreach (InventoryFolderBase folderBase in folders) + { + tempFolders.AddRange(getFolderHierarchy(folderBase.ID, cmd)); + } + if (tempFolders.Count > 0) + { + folders.AddRange(tempFolders); + } + } + return folders; + } + + /// + /// 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 (:folderID, :agentID, :parentFolderID, :folderName, :type, :version);"; + + string folderName = folder.Name; + if (folderName.Length > 64) + { + folderName = folderName.Substring(0, 64); + m_log.Warn("[INVENTORY DB]: Name field truncated from " + folder.Name.Length.ToString() + " to " + folderName.Length + " characters on add"); + } + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(database.CreateParameter("folderID", folder.ID)); + cmd.Parameters.Add(database.CreateParameter("agentID", folder.Owner)); + cmd.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID)); + cmd.Parameters.Add(database.CreateParameter("folderName", folderName)); + cmd.Parameters.Add(database.CreateParameter("type", folder.Type)); + cmd.Parameters.Add(database.CreateParameter("version", folder.Version)); + conn.Open(); + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.ErrorFormat("[INVENTORY DB]: Error : {0}", e.Message); + } + } + } + + /// + /// Updates an inventory folder + /// + /// Folder to update + public void updateInventoryFolder(InventoryFolderBase folder) + { + string sql = @"UPDATE inventoryfolders SET ""agentID"" = :agentID, + ""parentFolderID"" = :parentFolderID, + ""folderName"" = :folderName, + type = :type, + version = :version + WHERE folderID = :folderID"; + + string folderName = folder.Name; + if (folderName.Length > 64) + { + folderName = folderName.Substring(0, 64); + m_log.Warn("[INVENTORY DB]: Name field truncated from " + folder.Name.Length.ToString() + " to " + folderName.Length + " characters on update"); + } + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(database.CreateParameter("folderID", folder.ID)); + cmd.Parameters.Add(database.CreateParameter("agentID", folder.Owner)); + cmd.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID)); + cmd.Parameters.Add(database.CreateParameter("folderName", folderName)); + cmd.Parameters.Add(database.CreateParameter("type", folder.Type)); + cmd.Parameters.Add(database.CreateParameter("version", folder.Version)); + conn.Open(); + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.ErrorFormat("[INVENTORY DB]: Error : {0}", e.Message); + } + } + } + + /// + /// Updates an inventory folder + /// + /// Folder to update + public void moveInventoryFolder(InventoryFolderBase folder) + { + string sql = @"UPDATE inventoryfolders SET ""parentFolderID"" = :parentFolderID WHERE ""folderID"" = :folderID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID)); + cmd.Parameters.Add(database.CreateParameter("folderID", folder.ID)); + conn.Open(); + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.ErrorFormat("[INVENTORY DB]: Error : {0}", e.Message); + } + } + } + + /// + /// Delete an inventory folder + /// + /// Id of folder to delete + public void deleteInventoryFolder(UUID folderID) + { + string sql = @"SELECT * FROM inventoryfolders WHERE ""parentFolderID"" = :parentID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + List subFolders; + cmd.Parameters.Add(database.CreateParameter("parentID", UUID.Zero)); + conn.Open(); + subFolders = getFolderHierarchy(folderID, cmd); + + + //Delete all sub-folders + foreach (InventoryFolderBase f in subFolders) + { + DeleteOneFolder(f.ID, conn); + DeleteItemsInFolder(f.ID, conn); + } + + //Delete the actual row + DeleteOneFolder(folderID, conn); + DeleteItemsInFolder(folderID, conn); + } + } + + #endregion + + #region Item Methods + + /// + /// Returns a list of items in a specified folder + /// + /// The folder to search + /// A list containing inventory items + public List getInventoryInFolder(UUID folderID) + { + string sql = @"SELECT * FROM inventoryitems WHERE ""parentFolderID"" = :parentFolderID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(database.CreateParameter("parentFolderID", folderID)); + conn.Open(); + List items = new List(); + + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + items.Add(readInventoryItem(reader)); + } + } + return items; + } + } + + /// + /// Returns a specified inventory item + /// + /// The item ID + /// An inventory item + public InventoryItemBase getInventoryItem(UUID itemID) + { + string sql = @"SELECT * FROM inventoryitems WHERE ""inventoryID"" = :inventoryID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(database.CreateParameter("inventoryID", itemID)); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if (reader.Read()) + { + return readInventoryItem(reader); + } + } + } + + m_log.InfoFormat("[INVENTORY DB]: Found no inventory item with ID : {0}", itemID); + return null; + } + + /// + /// Adds a specified item to the database + /// + /// The inventory item + public void addInventoryItem(InventoryItemBase item) + { + if (getInventoryItem(item.ID) != null) + { + updateInventoryItem(item); + return; + } + + string sql = @"INSERT INTO inventoryitems + (""inventoryID"", ""assetID"", ""assetType"", ""parentFolderID"", ""avatarID"", ""inventoryName"", + ""inventoryDescription"", ""inventoryNextPermissions"", ""inventoryCurrentPermissions"", + ""invType"", ""creatorID"", ""inventoryBasePermissions"", ""inventoryEveryOnePermissions"", ""inventoryGroupPermissions"", + ""salePrice"", ""SaleType"", ""creationDate"", ""groupID"", ""groupOwned"", flags) + VALUES + (:inventoryID, :assetID, :assetType, :parentFolderID, :avatarID, :inventoryName, :inventoryDescription, + :inventoryNextPermissions, :inventoryCurrentPermissions, :invType, :creatorID, + :inventoryBasePermissions, :inventoryEveryOnePermissions, :inventoryGroupPermissions, :SalePrice, :SaleType, + :creationDate, :groupID, :groupOwned, :flags)"; + + string itemName = item.Name; + if (item.Name.Length > 64) + { + itemName = item.Name.Substring(0, 64); + m_log.Warn("[INVENTORY DB]: Name field truncated from " + item.Name.Length.ToString() + " to " + itemName.Length.ToString() + " characters"); + } + + string itemDesc = item.Description; + if (item.Description.Length > 128) + { + itemDesc = item.Description.Substring(0, 128); + m_log.Warn("[INVENTORY DB]: Description field truncated from " + item.Description.Length.ToString() + " to " + itemDesc.Length.ToString() + " characters"); + } + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) + { + command.Parameters.Add(database.CreateParameter("inventoryID", item.ID)); + command.Parameters.Add(database.CreateParameter("assetID", item.AssetID)); + command.Parameters.Add(database.CreateParameter("assetType", item.AssetType)); + command.Parameters.Add(database.CreateParameter("parentFolderID", item.Folder)); + command.Parameters.Add(database.CreateParameter("avatarID", item.Owner)); + command.Parameters.Add(database.CreateParameter("inventoryName", itemName)); + command.Parameters.Add(database.CreateParameter("inventoryDescription", itemDesc)); + command.Parameters.Add(database.CreateParameter("inventoryNextPermissions", item.NextPermissions)); + command.Parameters.Add(database.CreateParameter("inventoryCurrentPermissions", item.CurrentPermissions)); + command.Parameters.Add(database.CreateParameter("invType", item.InvType)); + command.Parameters.Add(database.CreateParameter("creatorID", item.CreatorId)); + command.Parameters.Add(database.CreateParameter("inventoryBasePermissions", item.BasePermissions)); + command.Parameters.Add(database.CreateParameter("inventoryEveryOnePermissions", item.EveryOnePermissions)); + command.Parameters.Add(database.CreateParameter("inventoryGroupPermissions", item.GroupPermissions)); + command.Parameters.Add(database.CreateParameter("SalePrice", item.SalePrice)); + command.Parameters.Add(database.CreateParameter("SaleType", item.SaleType)); + command.Parameters.Add(database.CreateParameter("creationDate", item.CreationDate)); + command.Parameters.Add(database.CreateParameter("groupID", item.GroupID)); + command.Parameters.Add(database.CreateParameter("groupOwned", item.GroupOwned)); + command.Parameters.Add(database.CreateParameter("flags", item.Flags)); + conn.Open(); + try + { + command.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.Error("[INVENTORY DB]: Error inserting item :" + e.Message); + } + } + + sql = @"UPDATE inventoryfolders SET version = version + 1 WHERE ""folderID"" = @folderID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) + { + command.Parameters.Add(database.CreateParameter("folderID", item.Folder.ToString())); + conn.Open(); + try + { + command.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.Error("[INVENTORY DB] Error updating inventory folder for new item :" + e.Message); + } + } + } + + /// + /// Updates the specified inventory item + /// + /// Inventory item to update + public void updateInventoryItem(InventoryItemBase item) + { + string sql = @"UPDATE inventoryitems SET ""assetID"" = :assetID, + ""assetType"" = :assetType, + ""parentFolderID"" = :parentFolderID, + ""avatarID"" = :avatarID, + ""inventoryName"" = :inventoryName, + ""inventoryDescription"" = :inventoryDescription, + ""inventoryNextPermissions"" = :inventoryNextPermissions, + ""inventoryCurrentPermissions"" = :inventoryCurrentPermissions, + ""invType"" = :invType, + ""creatorID"" = :creatorID, + ""inventoryBasePermissions"" = :inventoryBasePermissions, + ""inventoryEveryOnePermissions"" = :inventoryEveryOnePermissions, + ""inventoryGroupPermissions"" = :inventoryGroupPermissions, + ""salePrice"" = :SalePrice, + ""saleType"" = :SaleType, + ""creationDate"" = :creationDate, + ""groupID"" = :groupID, + ""groupOwned"" = :groupOwned, + flags = :flags + WHERE ""inventoryID"" = :inventoryID"; + + string itemName = item.Name; + if (item.Name.Length > 64) + { + itemName = item.Name.Substring(0, 64); + m_log.Warn("[INVENTORY DB]: Name field truncated from " + item.Name.Length.ToString() + " to " + itemName.Length.ToString() + " characters on update"); + } + + string itemDesc = item.Description; + if (item.Description.Length > 128) + { + itemDesc = item.Description.Substring(0, 128); + m_log.Warn("[INVENTORY DB]: Description field truncated from " + item.Description.Length.ToString() + " to " + itemDesc.Length.ToString() + " characters on update"); + } + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) + { + command.Parameters.Add(database.CreateParameter("inventoryID", item.ID)); + command.Parameters.Add(database.CreateParameter("assetID", item.AssetID)); + command.Parameters.Add(database.CreateParameter("assetType", item.AssetType)); + command.Parameters.Add(database.CreateParameter("parentFolderID", item.Folder)); + command.Parameters.Add(database.CreateParameter("avatarID", item.Owner)); + command.Parameters.Add(database.CreateParameter("inventoryName", itemName)); + command.Parameters.Add(database.CreateParameter("inventoryDescription", itemDesc)); + command.Parameters.Add(database.CreateParameter("inventoryNextPermissions", item.NextPermissions)); + command.Parameters.Add(database.CreateParameter("inventoryCurrentPermissions", item.CurrentPermissions)); + command.Parameters.Add(database.CreateParameter("invType", item.InvType)); + command.Parameters.Add(database.CreateParameter("creatorID", item.CreatorId)); + command.Parameters.Add(database.CreateParameter("inventoryBasePermissions", item.BasePermissions)); + command.Parameters.Add(database.CreateParameter("inventoryEveryOnePermissions", item.EveryOnePermissions)); + command.Parameters.Add(database.CreateParameter("inventoryGroupPermissions", item.GroupPermissions)); + command.Parameters.Add(database.CreateParameter("SalePrice", item.SalePrice)); + command.Parameters.Add(database.CreateParameter("SaleType", item.SaleType)); + command.Parameters.Add(database.CreateParameter("creationDate", item.CreationDate)); + command.Parameters.Add(database.CreateParameter("groupID", item.GroupID)); + command.Parameters.Add(database.CreateParameter("groupOwned", item.GroupOwned)); + command.Parameters.Add(database.CreateParameter("flags", item.Flags)); + conn.Open(); + try + { + command.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.Error("[INVENTORY DB]: Error updating item :" + e.Message); + } + } + } + + // See IInventoryDataPlugin + + /// + /// Delete an item in inventory database + /// + /// the item UUID + public void deleteInventoryItem(UUID itemID) + { + string sql = @"DELETE FROM inventoryitems WHERE ""inventoryID""=:inventoryID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(database.CreateParameter("inventoryID", itemID)); + try + { + conn.Open(); + cmd.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.Error("[INVENTORY DB]: Error deleting item :" + e.Message); + } + } + } + + public InventoryItemBase queryInventoryItem(UUID itemID) + { + return getInventoryItem(itemID); + } + + public InventoryFolderBase queryInventoryFolder(UUID folderID) + { + return getInventoryFolder(folderID); + } + + /// + /// Returns all activated gesture-items in the inventory of the specified avatar. + /// + /// The of the avatar + /// + /// The list of gestures (s) + /// + public List fetchActiveGestures(UUID avatarID) + { + string sql = @"SELECT * FROM inventoryitems WHERE ""avatarID"" = :uuid AND ""assetType"" = :assetType and flags = 1"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(database.CreateParameter("uuid", avatarID)); + cmd.Parameters.Add(database.CreateParameter("assetType", (int)AssetType.Gesture)); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + List gestureList = new List(); + while (reader.Read()) + { + gestureList.Add(readInventoryItem(reader)); + } + return gestureList; + } + } + } + + #endregion + + #region Private methods + + /// + /// Delete an item in inventory database + /// + /// the item ID + /// connection to the database + private void DeleteItemsInFolder(UUID folderID, NpgsqlConnection connection) + { + using (NpgsqlCommand command = new NpgsqlCommand(@"DELETE FROM inventoryitems WHERE ""folderID""=:folderID", connection)) + { + command.Parameters.Add(database.CreateParameter("folderID", folderID)); + + try + { + command.ExecuteNonQuery(); + } + catch (Exception e) + { + m_log.Error("[INVENTORY DB] Error deleting item :" + e.Message); + } + } + } + + /// + /// Gets the folder hierarchy in a loop. + /// + /// parent ID. + /// SQL command/connection to database + /// + private static List getFolderHierarchy(UUID parentID, NpgsqlCommand command) + { + command.Parameters["parentID"].Value = parentID.Guid; //.ToString(); + + List folders = getInventoryFolders(command); + + if (folders.Count > 0) + { + List tempFolders = new List(); + + foreach (InventoryFolderBase folderBase in folders) + { + tempFolders.AddRange(getFolderHierarchy(folderBase.ID, command)); + } + + if (tempFolders.Count > 0) + { + folders.AddRange(tempFolders); + } + } + return folders; + } + + /// + /// Gets the inventory folders. + /// + /// parentID, use UUID.Zero to get root + /// user id, use UUID.Zero, if you want all folders from a parentID. + /// + private List getInventoryFolders(UUID parentID, UUID user) + { + string sql = @"SELECT * FROM inventoryfolders WHERE ""parentFolderID"" = :parentID AND ""agentID"" = :uuid"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) + { + if (user == UUID.Zero) + { + command.Parameters.Add(database.CreateParameter("uuid", "%")); + } + else + { + command.Parameters.Add(database.CreateParameter("uuid", user)); + } + command.Parameters.Add(database.CreateParameter("parentID", parentID)); + conn.Open(); + return getInventoryFolders(command); + } + } + + /// + /// Gets the inventory folders. + /// + /// SQLcommand. + /// + private static List getInventoryFolders(NpgsqlCommand command) + { + using (NpgsqlDataReader reader = command.ExecuteReader()) + { + + List items = new List(); + while (reader.Read()) + { + items.Add(readInventoryFolder(reader)); + } + return items; + } + } + + /// + /// Reads a list of inventory folders returned by a query. + /// + /// A PGSQL Data Reader + /// A List containing inventory folders + protected static InventoryFolderBase readInventoryFolder(NpgsqlDataReader reader) + { + try + { + InventoryFolderBase folder = new InventoryFolderBase(); + folder.Owner = DBGuid.FromDB(reader["agentID"]); + folder.ParentID = DBGuid.FromDB(reader["parentFolderID"]); + folder.ID = DBGuid.FromDB(reader["folderID"]); + folder.Name = (string)reader["folderName"]; + folder.Type = (short)reader["type"]; + folder.Version = Convert.ToUInt16(reader["version"]); + + return folder; + } + catch (Exception e) + { + m_log.Error("[INVENTORY DB] Error reading inventory folder :" + e.Message); + } + + return null; + } + + /// + /// Reads a one item from an SQL result + /// + /// The SQL Result + /// the item read + private static InventoryItemBase readInventoryItem(IDataRecord reader) + { + try + { + InventoryItemBase item = new InventoryItemBase(); + + item.ID = DBGuid.FromDB(reader["inventoryID"]); + item.AssetID = DBGuid.FromDB(reader["assetID"]); + item.AssetType = Convert.ToInt32(reader["assetType"].ToString()); + item.Folder = DBGuid.FromDB(reader["parentFolderID"]); + item.Owner = DBGuid.FromDB(reader["avatarID"]); + item.Name = reader["inventoryName"].ToString(); + item.Description = reader["inventoryDescription"].ToString(); + item.NextPermissions = Convert.ToUInt32(reader["inventoryNextPermissions"]); + item.CurrentPermissions = Convert.ToUInt32(reader["inventoryCurrentPermissions"]); + item.InvType = Convert.ToInt32(reader["invType"].ToString()); + item.CreatorId = reader["creatorID"].ToString(); + item.BasePermissions = Convert.ToUInt32(reader["inventoryBasePermissions"]); + item.EveryOnePermissions = Convert.ToUInt32(reader["inventoryEveryOnePermissions"]); + item.GroupPermissions = Convert.ToUInt32(reader["inventoryGroupPermissions"]); + item.SalePrice = Convert.ToInt32(reader["salePrice"]); + item.SaleType = Convert.ToByte(reader["saleType"]); + item.CreationDate = Convert.ToInt32(reader["creationDate"]); + item.GroupID = DBGuid.FromDB(reader["groupID"]); + item.GroupOwned = Convert.ToBoolean(reader["groupOwned"]); + item.Flags = Convert.ToUInt32(reader["flags"]); + + return item; + } + catch (NpgsqlException e) + { + m_log.Error("[INVENTORY DB]: Error reading inventory item :" + e.Message); + } + + return null; + } + + /// + /// Delete a folder in inventory databasae + /// + /// the folder UUID + /// connection to database + private void DeleteOneFolder(UUID folderID, NpgsqlConnection connection) + { + try + { + using (NpgsqlCommand command = new NpgsqlCommand(@"DELETE FROM inventoryfolders WHERE ""folderID""=:folderID and type=-1", connection)) + { + command.Parameters.Add(database.CreateParameter("folderID", folderID)); + + command.ExecuteNonQuery(); + } + } + catch (NpgsqlException e) + { + m_log.Error("[INVENTORY DB]: Error deleting folder :" + e.Message); + } + } + + #endregion + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLManager.cs b/OpenSim/Data/PGSQL/PGSQLManager.cs new file mode 100644 index 0000000000..3ddaf38693 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLManager.cs @@ -0,0 +1,321 @@ +/* + * 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 OpenSimulator 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.IO; +using System.Reflection; +using log4net; +using OpenMetaverse; +using Npgsql; +using NpgsqlTypes; + +namespace OpenSim.Data.PGSQL +{ + /// + /// A management class for the MS SQL Storage Engine + /// + public class PGSQLManager + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// Connection string for ADO.net + /// + private readonly string connectionString; + + /// + /// Initialize the manager and set the connectionstring + /// + /// + public PGSQLManager(string connection) + { + connectionString = connection; + } + + /// + /// Type conversion to a SQLDbType functions + /// + /// + /// + internal NpgsqlDbType DbtypeFromType(Type type) + { + if (type == typeof(string)) + { + return NpgsqlDbType.Varchar; + } + if (type == typeof(double)) + { + return NpgsqlDbType.Double; + } + if (type == typeof(Single)) + { + return NpgsqlDbType.Double; + } + if (type == typeof(int)) + { + return NpgsqlDbType.Integer; + } + if (type == typeof(bool)) + { + return NpgsqlDbType.Boolean; + } + if (type == typeof(UUID)) + { + return NpgsqlDbType.Uuid; + } + if (type == typeof(byte)) + { + return NpgsqlDbType.Smallint; + } + if (type == typeof(sbyte)) + { + return NpgsqlDbType.Integer; + } + if (type == typeof(Byte[])) + { + return NpgsqlDbType.Bytea; + } + if (type == typeof(uint) || type == typeof(ushort)) + { + return NpgsqlDbType.Integer; + } + if (type == typeof(ulong)) + { + return NpgsqlDbType.Bigint; + } + if (type == typeof(DateTime)) + { + return NpgsqlDbType.Timestamp; + } + + return NpgsqlDbType.Varchar; + } + + internal NpgsqlDbType DbtypeFromString(Type type, string PGFieldType) + { + if (PGFieldType == "") + { + return DbtypeFromType(type); + } + + if (PGFieldType == "character varying") + { + return NpgsqlDbType.Varchar; + } + if (PGFieldType == "double precision") + { + return NpgsqlDbType.Double; + } + if (PGFieldType == "integer") + { + return NpgsqlDbType.Integer; + } + if (PGFieldType == "smallint") + { + return NpgsqlDbType.Smallint; + } + if (PGFieldType == "boolean") + { + return NpgsqlDbType.Boolean; + } + if (PGFieldType == "uuid") + { + return NpgsqlDbType.Uuid; + } + if (PGFieldType == "bytea") + { + return NpgsqlDbType.Bytea; + } + + return DbtypeFromType(type); + } + + /// + /// Creates value for parameter. + /// + /// The value. + /// + private static object CreateParameterValue(object value) + { + Type valueType = value.GetType(); + + if (valueType == typeof(UUID)) //TODO check if this works + { + return ((UUID) value).Guid; + } + if (valueType == typeof(UUID)) + { + return ((UUID)value).Guid; + } + if (valueType == typeof(bool)) + { + return (bool)value; + } + if (valueType == typeof(Byte[])) + { + return value; + } + if (valueType == typeof(int)) + { + return value; + } + return value; + } + + /// + /// Create value for parameter based on PGSQL Schema + /// + /// + /// + /// + internal static object CreateParameterValue(object value, string PGFieldType) + { + if (PGFieldType == "uuid") + { + UUID uidout; + UUID.TryParse(value.ToString(), out uidout); + return uidout; + } + if (PGFieldType == "integer") + { + int intout; + int.TryParse(value.ToString(), out intout); + return intout; + } + if (PGFieldType == "boolean") + { + return (value.ToString() == "true"); + } + if (PGFieldType == "timestamp with time zone") + { + return (DateTime)value; + } + if (PGFieldType == "timestamp without time zone") + { + return (DateTime)value; + } + return CreateParameterValue(value); + } + + /// + /// Create a parameter for a command + /// + /// Name of the parameter. + /// parameter object. + /// + internal NpgsqlParameter CreateParameter(string parameterName, object parameterObject) + { + return CreateParameter(parameterName, parameterObject, false); + } + + /// + /// Creates the parameter for a command. + /// + /// Name of the parameter. + /// parameter object. + /// if set to true parameter is a output parameter + /// + internal NpgsqlParameter CreateParameter(string parameterName, object parameterObject, bool parameterOut) + { + //Tweak so we dont always have to add : sign + if (parameterName.StartsWith(":")) parameterName = parameterName.Replace(":",""); + + //HACK if object is null, it is turned into a string, there are no nullable type till now + if (parameterObject == null) parameterObject = ""; + + NpgsqlParameter parameter = new NpgsqlParameter(parameterName, DbtypeFromType(parameterObject.GetType())); + + if (parameterOut) + { + parameter.Direction = ParameterDirection.Output; + } + else + { + parameter.Direction = ParameterDirection.Input; + parameter.Value = CreateParameterValue(parameterObject); + } + + return parameter; + } + + /// + /// Create a parameter with PGSQL schema type + /// + /// + /// + /// + /// + internal NpgsqlParameter CreateParameter(string parameterName, object parameterObject, string PGFieldType) + { + //Tweak so we dont always have to add : sign + if (parameterName.StartsWith(":")) parameterName = parameterName.Replace(":", ""); + + //HACK if object is null, it is turned into a string, there are no nullable type till now + if (parameterObject == null) parameterObject = ""; + + NpgsqlParameter parameter = new NpgsqlParameter(parameterName, DbtypeFromString(parameterObject.GetType(), PGFieldType)); + + parameter.Direction = ParameterDirection.Input; + parameter.Value = CreateParameterValue(parameterObject, PGFieldType); + + return parameter; + } + + /// + /// Checks if we need to do some migrations to the database + /// + /// migrationStore. + public void CheckMigration(string migrationStore) + { + using (NpgsqlConnection connection = new NpgsqlConnection(connectionString)) + { + connection.Open(); + Assembly assem = GetType().Assembly; + PGSQLMigration migration = new PGSQLMigration(connection, assem, migrationStore); + + migration.Update(); + } + } + + /// + /// 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/PGSQL/PGSQLMigration.cs b/OpenSim/Data/PGSQL/PGSQLMigration.cs new file mode 100644 index 0000000000..709fde04f2 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLMigration.cs @@ -0,0 +1,102 @@ +/* + * 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 OpenSimulator 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 Npgsql; +using System; +using System.Data; +using System.Data.Common; +using System.Reflection; + +namespace OpenSim.Data.PGSQL +{ + public class PGSQLMigration : Migration + { + public PGSQLMigration(NpgsqlConnection conn, Assembly assem, string type) + : base(conn, assem, type) + { + } + + public PGSQLMigration(NpgsqlConnection conn, Assembly assem, string subtype, string type) + : base(conn, assem, subtype, type) + { + } + + protected override int FindVersion(DbConnection conn, string type) + { + int version = 0; + NpgsqlConnection lcConn = (NpgsqlConnection)conn; + + using (NpgsqlCommand cmd = lcConn.CreateCommand()) + { + try + { + cmd.CommandText = "select version from migrations where name = '" + type + "' " + + " order by version desc limit 1"; //Must be + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if (reader.Read()) + { + version = Convert.ToInt32(reader["version"]); + } + reader.Close(); + } + } + catch + { + // Return -1 to indicate table does not exist + return -1; + } + } + return version; + } + + protected override void ExecuteScript(DbConnection conn, string[] script) + { + if (!(conn is NpgsqlConnection)) + { + base.ExecuteScript(conn, script); + return; + } + + foreach (string sql in script) + { + try + { + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, (NpgsqlConnection)conn)) + { + cmd.ExecuteNonQuery(); + } + } + catch (Exception) + { + throw new Exception(sql); + + } + } + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLOfflineIMData.cs b/OpenSim/Data/PGSQL/PGSQLOfflineIMData.cs new file mode 100644 index 0000000000..82e5ed829e --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLOfflineIMData.cs @@ -0,0 +1,56 @@ +/* + * 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 OpenSimulator 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; +using System.Collections.Generic; +using System.Reflection; +using OpenSim.Framework; +using OpenMetaverse; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + public class PGSQLOfflineIMData : PGSQLGenericTableHandler, IOfflineIMData + { + public PGSQLOfflineIMData(string connectionString, string realm) + : base(connectionString, realm, "IM_Store") + { + } + + public void DeleteOld() + { + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + cmd.CommandText = String.Format("delete from {0} where \"TMStamp\" < CURRENT_DATE - INTERVAL '2 week'", m_Realm); + + ExecuteNonQuery(cmd); + } + + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLPresenceData.cs b/OpenSim/Data/PGSQL/PGSQLPresenceData.cs new file mode 100644 index 0000000000..666de07c0d --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLPresenceData.cs @@ -0,0 +1,115 @@ +/* + * 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 OpenSimulator 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.Reflection; +using System.Threading; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + /// + /// A PGSQL Interface for the Presence Server + /// + public class PGSQLPresenceData : PGSQLGenericTableHandler, + IPresenceData + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public PGSQLPresenceData(string connectionString, string realm) : + base(connectionString, realm, "Presence") + { + } + + public PresenceData Get(UUID sessionID) + { + PresenceData[] ret = Get("SessionID", sessionID.ToString()); + + if (ret.Length == 0) + return null; + + return ret[0]; + } + + public void LogoutRegionAgents(UUID regionID) + { + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + + cmd.CommandText = String.Format(@"DELETE FROM {0} WHERE ""RegionID""=:RegionID", m_Realm); + + cmd.Parameters.Add(m_database.CreateParameter("RegionID", regionID)); + cmd.Connection = conn; + conn.Open(); + cmd.ExecuteNonQuery(); + } + } + + public bool ReportAgent(UUID sessionID, UUID regionID) + { + PresenceData[] pd = Get("SessionID", sessionID.ToString()); + if (pd.Length == 0) + return false; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + + cmd.CommandText = String.Format(@"UPDATE {0} SET + ""RegionID"" = :RegionID + WHERE ""SessionID"" = :SessionID", m_Realm); + + cmd.Parameters.Add(m_database.CreateParameter("SessionID", sessionID)); + cmd.Parameters.Add(m_database.CreateParameter("RegionID", regionID)); + cmd.Connection = conn; + conn.Open(); + if (cmd.ExecuteNonQuery() == 0) + return false; + } + return true; + } + + public bool VerifyAgent(UUID agentId, UUID secureSessionID) + { + PresenceData[] ret = Get("SecureSessionID", secureSessionID.ToString()); + + if (ret.Length == 0) + return false; + + if(ret[0].UserID != agentId.ToString()) + return false; + + return true; + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLRegionData.cs b/OpenSim/Data/PGSQL/PGSQLRegionData.cs new file mode 100644 index 0000000000..8a46559478 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLRegionData.cs @@ -0,0 +1,392 @@ +/* + * 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 OpenSimulator 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.Drawing; +using System.IO; +using System.Reflection; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using RegionFlags = OpenSim.Framework.RegionFlags; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + /// + /// A PGSQL Interface for the Region Server. + /// + public class PGSQLRegionData : IRegionData + { + private string m_Realm; + private List m_ColumnNames = null; + private string m_ConnectionString; + private PGSQLManager m_database; + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected Dictionary m_FieldTypes = new Dictionary(); + + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + + public PGSQLRegionData(string connectionString, string realm) + { + m_Realm = realm; + m_ConnectionString = connectionString; + m_database = new PGSQLManager(connectionString); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + { + conn.Open(); + Migration m = new Migration(conn, GetType().Assembly, "GridStore"); + m.Update(); + } + LoadFieldTypes(); + } + + private void LoadFieldTypes() + { + m_FieldTypes = new Dictionary(); + + string query = string.Format(@"select column_name,data_type + from INFORMATION_SCHEMA.COLUMNS + where table_name = lower('{0}'); + + ", m_Realm); + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) + { + conn.Open(); + using (NpgsqlDataReader rdr = cmd.ExecuteReader()) + { + while (rdr.Read()) + { + // query produces 0 to many rows of single column, so always add the first item in each row + m_FieldTypes.Add((string)rdr[0], (string)rdr[1]); + } + } + } + } + + public List Get(string regionName, UUID scopeID) + { + string sql = "select * from "+m_Realm+" where lower(\"regionName\") like lower(:regionName) "; + if (scopeID != UUID.Zero) + sql += " and \"ScopeID\" = :scopeID"; + sql += " order by lower(\"regionName\")"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("regionName", regionName)); + if (scopeID != UUID.Zero) + cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); + conn.Open(); + return RunCommand(cmd); + } + } + + public RegionData Get(int posX, int posY, UUID scopeID) + { + string sql = "select * from "+m_Realm+" where \"locX\" = :posX and \"locY\" = :posY"; + if (scopeID != UUID.Zero) + sql += " and \"ScopeID\" = :scopeID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("posX", posX)); + cmd.Parameters.Add(m_database.CreateParameter("posY", posY)); + if (scopeID != UUID.Zero) + cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); + conn.Open(); + List ret = RunCommand(cmd); + if (ret.Count == 0) + return null; + + return ret[0]; + } + } + + public RegionData Get(UUID regionID, UUID scopeID) + { + string sql = "select * from "+m_Realm+" where uuid = :regionID"; + if (scopeID != UUID.Zero) + sql += " and \"ScopeID\" = :scopeID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("regionID", regionID)); + if (scopeID != UUID.Zero) + cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); + conn.Open(); + List ret = RunCommand(cmd); + if (ret.Count == 0) + return null; + + return ret[0]; + } + } + + public List Get(int startX, int startY, int endX, int endY, UUID scopeID) + { + string sql = "select * from "+m_Realm+" where \"locX\" between :startX and :endX and \"locY\" between :startY and :endY"; + if (scopeID != UUID.Zero) + sql += " and \"ScopeID\" = :scopeID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("startX", startX)); + cmd.Parameters.Add(m_database.CreateParameter("startY", startY)); + cmd.Parameters.Add(m_database.CreateParameter("endX", endX)); + cmd.Parameters.Add(m_database.CreateParameter("endY", endY)); + cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); + conn.Open(); + return RunCommand(cmd); + } + } + + public List RunCommand(NpgsqlCommand cmd) + { + List retList = new List(); + + NpgsqlDataReader result = cmd.ExecuteReader(); + + while (result.Read()) + { + RegionData ret = new RegionData(); + ret.Data = new Dictionary(); + + UUID regionID; + UUID.TryParse(result["uuid"].ToString(), out regionID); + ret.RegionID = regionID; + UUID scope; + UUID.TryParse(result["ScopeID"].ToString(), out scope); + ret.ScopeID = scope; + ret.RegionName = result["regionName"].ToString(); + ret.posX = Convert.ToInt32(result["locX"]); + ret.posY = Convert.ToInt32(result["locY"]); + ret.sizeX = Convert.ToInt32(result["sizeX"]); + ret.sizeY = Convert.ToInt32(result["sizeY"]); + + if (m_ColumnNames == null) + { + m_ColumnNames = new List(); + + DataTable schemaTable = result.GetSchemaTable(); + foreach (DataRow row in schemaTable.Rows) + m_ColumnNames.Add(row["ColumnName"].ToString()); + } + + foreach (string s in m_ColumnNames) + { + if (s == "uuid") + continue; + if (s == "ScopeID") + continue; + if (s == "regionName") + continue; + if (s == "locX") + continue; + if (s == "locY") + continue; + + ret.Data[s] = result[s].ToString(); + } + + retList.Add(ret); + } + return retList; + } + + public bool Store(RegionData data) + { + if (data.Data.ContainsKey("uuid")) + data.Data.Remove("uuid"); + if (data.Data.ContainsKey("ScopeID")) + data.Data.Remove("ScopeID"); + if (data.Data.ContainsKey("regionName")) + data.Data.Remove("regionName"); + if (data.Data.ContainsKey("posX")) + data.Data.Remove("posX"); + if (data.Data.ContainsKey("posY")) + data.Data.Remove("posY"); + if (data.Data.ContainsKey("sizeX")) + data.Data.Remove("sizeX"); + if (data.Data.ContainsKey("sizeY")) + data.Data.Remove("sizeY"); + if (data.Data.ContainsKey("locX")) + data.Data.Remove("locX"); + if (data.Data.ContainsKey("locY")) + data.Data.Remove("locY"); + + string[] fields = new List(data.Data.Keys).ToArray(); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + + string update = "update " + m_Realm + " set \"locX\"=:posX, \"locY\"=:posY, \"sizeX\"=:sizeX, \"sizeY\"=:sizeY "; + + foreach (string field in fields) + { + + update += ", "; + update += " \"" + field + "\" = :" + field; + + if (m_FieldTypes.ContainsKey(field)) + cmd.Parameters.Add(m_database.CreateParameter(field, data.Data[field], m_FieldTypes[field])); + else + cmd.Parameters.Add(m_database.CreateParameter(field, data.Data[field])); + } + + update += " where uuid = :regionID"; + + if (data.ScopeID != UUID.Zero) + update += " and \"ScopeID\" = :scopeID"; + + cmd.CommandText = update; + cmd.Connection = conn; + cmd.Parameters.Add(m_database.CreateParameter("regionID", data.RegionID)); + cmd.Parameters.Add(m_database.CreateParameter("regionName", data.RegionName)); + cmd.Parameters.Add(m_database.CreateParameter("scopeID", data.ScopeID)); + cmd.Parameters.Add(m_database.CreateParameter("posX", data.posX)); + cmd.Parameters.Add(m_database.CreateParameter("posY", data.posY)); + cmd.Parameters.Add(m_database.CreateParameter("sizeX", data.sizeX)); + cmd.Parameters.Add(m_database.CreateParameter("sizeY", data.sizeY)); + conn.Open(); + try + { + if (cmd.ExecuteNonQuery() < 1) + { + string insert = "insert into " + m_Realm + " (uuid, \"ScopeID\", \"locX\", \"locY\", \"sizeX\", \"sizeY\", \"regionName\", \"" + + String.Join("\", \"", fields) + + "\") values (:regionID, :scopeID, :posX, :posY, :sizeX, :sizeY, :regionName, :" + String.Join(", :", fields) + ")"; + + cmd.CommandText = insert; + + try + { + if (cmd.ExecuteNonQuery() < 1) + { + return false; + } + } + catch (Exception ex) + { + m_log.Warn("[PGSQL Grid]: Error inserting into Regions table: " + ex.Message + ", INSERT sql: " + insert); + } + } + } + catch (Exception ex) + { + m_log.Warn("[PGSQL Grid]: Error updating Regions table: " + ex.Message + ", UPDATE sql: " + update); + } + } + + return true; + } + + public bool SetDataItem(UUID regionID, string item, string value) + { + string sql = "update " + m_Realm + + " set \"" + item + "\" = :" + item + " where uuid = :UUID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("" + item, value)); + cmd.Parameters.Add(m_database.CreateParameter("UUID", regionID)); + conn.Open(); + if (cmd.ExecuteNonQuery() > 0) + return true; + } + return false; + } + + public bool Delete(UUID regionID) + { + string sql = "delete from " + m_Realm + + " where uuid = :UUID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("UUID", regionID)); + conn.Open(); + if (cmd.ExecuteNonQuery() > 0) + return true; + } + return false; + } + + public List GetDefaultRegions(UUID scopeID) + { + return Get((int)RegionFlags.DefaultRegion, scopeID); + } + + public List GetDefaultHypergridRegions(UUID scopeID) + { + return Get((int)RegionFlags.DefaultHGRegion, scopeID); + } + + public List GetFallbackRegions(UUID scopeID, int x, int y) + { + List regions = Get((int)RegionFlags.FallbackRegion, scopeID); + RegionDataDistanceCompare distanceComparer = new RegionDataDistanceCompare(x, y); + regions.Sort(distanceComparer); + + return regions; + } + + public List GetHyperlinks(UUID scopeID) + { + return Get((int)RegionFlags.Hyperlink, scopeID); + } + + private List Get(int regionFlags, UUID scopeID) + { + string sql = "SELECT * FROM " + m_Realm + " WHERE (flags & " + regionFlags.ToString() + ") <> 0"; + if (scopeID != UUID.Zero) + sql += " AND \"ScopeID\" = :scopeID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); + conn.Open(); + return RunCommand(cmd); + } + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLSimulationData.cs b/OpenSim/Data/PGSQL/PGSQLSimulationData.cs new file mode 100644 index 0000000000..5753ae31bb --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLSimulationData.cs @@ -0,0 +1,2247 @@ +/* + * 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 OpenSimulator 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.Drawing; +using System.IO; +using System.Reflection; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + /// + /// A PGSQL Interface for the Region Server. + /// + public class PGSQLSimulationData : ISimulationDataStore + { + private const string _migrationStore = "RegionStore"; + + // private static FileSystemDataStore Instance = new FileSystemDataStore(); + private static readonly ILog _Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// The database manager + /// + private PGSQLManager _Database; + private string m_connectionString; + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + + public PGSQLSimulationData() + { + } + + public PGSQLSimulationData(string connectionString) + { + Initialise(connectionString); + } + + /// + /// Initialises the region datastore + /// + /// The connection string. + public void Initialise(string connectionString) + { + m_connectionString = connectionString; + _Database = new PGSQLManager(connectionString); + + using (NpgsqlConnection conn = new NpgsqlConnection(connectionString)) + { + conn.Open(); + //New Migration settings + Migration m = new Migration(conn, Assembly, "RegionStore"); + m.Update(); + } + } + + /// + /// Dispose the database + /// + public void Dispose() { } + + #region SceneObjectGroup region for loading and Store of the scene. + + /// + /// Loads the objects present in the region. + /// + /// The region UUID. + /// + public List LoadObjects(UUID regionUUID) + { + UUID lastGroupID = UUID.Zero; + + Dictionary prims = new Dictionary(); + Dictionary objects = new Dictionary(); + SceneObjectGroup grp = null; + + string sql = @"SELECT *, + CASE WHEN prims.""UUID"" = prims.""SceneGroupID"" THEN 0 ELSE 1 END as sort + FROM prims + LEFT JOIN primshapes ON prims.""UUID"" = primshapes.""UUID"" + WHERE ""RegionUUID"" = :RegionUUID + ORDER BY ""SceneGroupID"" asc, sort asc, ""LinkNumber"" asc"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) + { + command.Parameters.Add(_Database.CreateParameter("regionUUID", regionUUID)); + conn.Open(); + using (NpgsqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + SceneObjectPart sceneObjectPart = BuildPrim(reader); + if (reader["Shape"] is DBNull) + sceneObjectPart.Shape = PrimitiveBaseShape.Default; + else + sceneObjectPart.Shape = BuildShape(reader); + + prims[sceneObjectPart.UUID] = sceneObjectPart; + + UUID groupID = new UUID((Guid)reader["SceneGroupID"]); + + if (groupID != lastGroupID) // New SOG + { + if (grp != null) + objects[grp.UUID] = grp; + + lastGroupID = groupID; + + // There sometimes exist OpenSim bugs that 'orphan groups' so that none of the prims are + // recorded as the root prim (for which the UUID must equal the persisted group UUID). In + // this case, force the UUID to be the same as the group UUID so that at least these can be + // deleted (we need to change the UUID so that any other prims in the linkset can also be + // deleted). + if (sceneObjectPart.UUID != groupID && groupID != UUID.Zero) + { + _Log.WarnFormat( + "[REGION DB]: Found root prim {0} {1} at {2} where group was actually {3}. Forcing UUID to group UUID", + sceneObjectPart.Name, sceneObjectPart.UUID, sceneObjectPart.GroupPosition, groupID); + + sceneObjectPart.UUID = groupID; + } + + grp = new SceneObjectGroup(sceneObjectPart); + } + else + { + // Black magic to preserve link numbers + // Why is this needed, fix this in AddPart method. + int link = sceneObjectPart.LinkNum; + + grp.AddPart(sceneObjectPart); + + if (link != 0) + sceneObjectPart.LinkNum = link; + } + } + } + } + + if (grp != null) + objects[grp.UUID] = grp; + + // Instead of attempting to LoadItems on every prim, + // most of which probably have no items... get a + // list from DB of all prims which have items and + // LoadItems only on those + List primsWithInventory = new List(); + string qry = "select distinct \"primID\" from primitems"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand command = new NpgsqlCommand(qry, conn)) + { + conn.Open(); + using (NpgsqlDataReader itemReader = command.ExecuteReader()) + { + while (itemReader.Read()) + { + if (!(itemReader["primID"] is DBNull)) + { + UUID primID = new UUID(itemReader["primID"].ToString()); + if (prims.ContainsKey(primID)) + { + primsWithInventory.Add(prims[primID]); + } + } + } + } + } + + LoadItems(primsWithInventory); + + _Log.DebugFormat("[REGION DB]: Loaded {0} objects using {1} prims", objects.Count, prims.Count); + + return new List(objects.Values); + } + + /// + /// Load in the prim's persisted inventory. + /// + /// all prims with inventory on a region + private void LoadItems(List allPrimsWithInventory) + { + string sql = @"SELECT * FROM primitems WHERE ""primID"" = :PrimID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) + { + conn.Open(); + foreach (SceneObjectPart objectPart in allPrimsWithInventory) + { + command.Parameters.Clear(); + command.Parameters.Add(_Database.CreateParameter("PrimID", objectPart.UUID)); + + List inventory = new List(); + + using (NpgsqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + TaskInventoryItem item = BuildItem(reader); + + item.ParentID = objectPart.UUID; // Values in database are + // often wrong + inventory.Add(item); + } + } + + objectPart.Inventory.RestoreInventoryItems(inventory); + } + } + } + + /// + /// Stores all object's details apart from inventory + /// + /// + /// + public void StoreObject(SceneObjectGroup obj, UUID regionUUID) + { + uint flags = obj.RootPart.GetEffectiveObjectFlags(); + // Eligibility check + // + if ((flags & (uint)PrimFlags.Temporary) != 0) + return; + if ((flags & (uint)PrimFlags.TemporaryOnRez) != 0) + return; + + //_Log.DebugFormat("[PGSQL]: Adding/Changing SceneObjectGroup: {0} to region: {1}, object has {2} prims.", obj.UUID, regionUUID, obj.Parts.Length); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + NpgsqlTransaction transaction = conn.BeginTransaction(); + + try + { + foreach (SceneObjectPart sceneObjectPart in obj.Parts) + { + //Update prim + using (NpgsqlCommand sqlCommand = conn.CreateCommand()) + { + sqlCommand.Transaction = transaction; + try + { + StoreSceneObjectPrim(sceneObjectPart, sqlCommand, obj.UUID, regionUUID); + } + catch (NpgsqlException sqlEx) + { + _Log.ErrorFormat("[REGION DB]: Store SceneObjectPrim SQL error: {0} at line {1}", sqlEx.Message, sqlEx.Line); + throw; + } + } + + //Update primshapes + using (NpgsqlCommand sqlCommand = conn.CreateCommand()) + { + sqlCommand.Transaction = transaction; + try + { + StoreSceneObjectPrimShapes(sceneObjectPart, sqlCommand, obj.UUID, regionUUID); + } + catch (NpgsqlException sqlEx) + { + _Log.ErrorFormat("[REGION DB]: Store SceneObjectPrimShapes SQL error: {0} at line {1}", sqlEx.Message, sqlEx.Line); + throw; + } + } + } + + transaction.Commit(); + } + catch (Exception ex) + { + _Log.ErrorFormat("[REGION DB]: Store SceneObjectGroup error: {0}, Rolling back...", ex.Message); + try + { + transaction.Rollback(); + } + catch (Exception ex2) + { + //Show error + _Log.InfoFormat("[REGION DB]: Rollback of SceneObjectGroup store transaction failed with error: {0}", ex2.Message); + + } + } + } + } + + /// + /// Stores the prim of the sceneobjectpart. + /// + /// The sceneobjectpart or prim. + /// The SQL command with the transaction. + /// The scenegroup UUID. + /// The region UUID. + private void StoreSceneObjectPrim(SceneObjectPart sceneObjectPart, NpgsqlCommand sqlCommand, UUID sceneGroupID, UUID regionUUID) + { + //Big query to update or insert a new prim. + + string queryPrims = @" + UPDATE prims SET + ""CreationDate"" = :CreationDate, ""Name"" = :Name, ""Text"" = :Text, ""Description"" = :Description, ""SitName"" = :SitName, + ""TouchName"" = :TouchName, ""ObjectFlags"" = :ObjectFlags, ""OwnerMask"" = :OwnerMask, ""NextOwnerMask"" = :NextOwnerMask, ""GroupMask"" = :GroupMask, + ""EveryoneMask"" = :EveryoneMask, ""BaseMask"" = :BaseMask, ""PositionX"" = :PositionX, ""PositionY"" = :PositionY, ""PositionZ"" = :PositionZ, + ""GroupPositionX"" = :GroupPositionX, ""GroupPositionY"" = :GroupPositionY, ""GroupPositionZ"" = :GroupPositionZ, ""VelocityX"" = :VelocityX, + ""VelocityY"" = :VelocityY, ""VelocityZ"" = :VelocityZ, ""AngularVelocityX"" = :AngularVelocityX, ""AngularVelocityY"" = :AngularVelocityY, + ""AngularVelocityZ"" = :AngularVelocityZ, ""AccelerationX"" = :AccelerationX, ""AccelerationY"" = :AccelerationY, + ""AccelerationZ"" = :AccelerationZ, ""RotationX"" = :RotationX, ""RotationY"" = :RotationY, ""RotationZ"" = :RotationZ, ""RotationW"" = :RotationW, + ""SitTargetOffsetX"" = :SitTargetOffsetX, ""SitTargetOffsetY"" = :SitTargetOffsetY, ""SitTargetOffsetZ"" = :SitTargetOffsetZ, + ""SitTargetOrientW"" = :SitTargetOrientW, ""SitTargetOrientX"" = :SitTargetOrientX, ""SitTargetOrientY"" = :SitTargetOrientY, + ""SitTargetOrientZ"" = :SitTargetOrientZ, ""RegionUUID"" = :RegionUUID, ""CreatorID"" = :CreatorID, ""OwnerID"" = :OwnerID, ""GroupID"" = :GroupID, + ""LastOwnerID"" = :LastOwnerID, ""SceneGroupID"" = :SceneGroupID, ""PayPrice"" = :PayPrice, ""PayButton1"" = :PayButton1, ""PayButton2"" = :PayButton2, + ""PayButton3"" = :PayButton3, ""PayButton4"" = :PayButton4, ""LoopedSound"" = :LoopedSound, ""LoopedSoundGain"" = :LoopedSoundGain, + ""TextureAnimation"" = :TextureAnimation, ""OmegaX"" = :OmegaX, ""OmegaY"" = :OmegaY, ""OmegaZ"" = :OmegaZ, ""CameraEyeOffsetX"" = :CameraEyeOffsetX, + ""CameraEyeOffsetY"" = :CameraEyeOffsetY, ""CameraEyeOffsetZ"" = :CameraEyeOffsetZ, ""CameraAtOffsetX"" = :CameraAtOffsetX, + ""CameraAtOffsetY"" = :CameraAtOffsetY, ""CameraAtOffsetZ"" = :CameraAtOffsetZ, ""ForceMouselook"" = :ForceMouselook, + ""ScriptAccessPin"" = :ScriptAccessPin, ""AllowedDrop"" = :AllowedDrop, ""DieAtEdge"" = :DieAtEdge, ""SalePrice"" = :SalePrice, + ""SaleType"" = :SaleType, ""ColorR"" = :ColorR, ""ColorG"" = :ColorG, ""ColorB"" = :ColorB, ""ColorA"" = :ColorA, ""ParticleSystem"" = :ParticleSystem, + ""ClickAction"" = :ClickAction, ""Material"" = :Material, ""CollisionSound"" = :CollisionSound, ""CollisionSoundVolume"" = :CollisionSoundVolume, ""PassTouches"" = :PassTouches, + ""LinkNumber"" = :LinkNumber, ""MediaURL"" = :MediaURL, ""DynAttrs"" = :DynAttrs, + ""PhysicsShapeType"" = :PhysicsShapeType, ""Density"" = :Density, ""GravityModifier"" = :GravityModifier, ""Friction"" = :Friction, ""Restitution"" = :Restitution + WHERE ""UUID"" = :UUID ; + + INSERT INTO + prims ( + ""UUID"", ""CreationDate"", ""Name"", ""Text"", ""Description"", ""SitName"", ""TouchName"", ""ObjectFlags"", ""OwnerMask"", ""NextOwnerMask"", ""GroupMask"", + ""EveryoneMask"", ""BaseMask"", ""PositionX"", ""PositionY"", ""PositionZ"", ""GroupPositionX"", ""GroupPositionY"", ""GroupPositionZ"", ""VelocityX"", + ""VelocityY"", ""VelocityZ"", ""AngularVelocityX"", ""AngularVelocityY"", ""AngularVelocityZ"", ""AccelerationX"", ""AccelerationY"", ""AccelerationZ"", + ""RotationX"", ""RotationY"", ""RotationZ"", ""RotationW"", ""SitTargetOffsetX"", ""SitTargetOffsetY"", ""SitTargetOffsetZ"", ""SitTargetOrientW"", + ""SitTargetOrientX"", ""SitTargetOrientY"", ""SitTargetOrientZ"", ""RegionUUID"", ""CreatorID"", ""OwnerID"", ""GroupID"", ""LastOwnerID"", ""SceneGroupID"", + ""PayPrice"", ""PayButton1"", ""PayButton2"", ""PayButton3"", ""PayButton4"", ""LoopedSound"", ""LoopedSoundGain"", ""TextureAnimation"", ""OmegaX"", + ""OmegaY"", ""OmegaZ"", ""CameraEyeOffsetX"", ""CameraEyeOffsetY"", ""CameraEyeOffsetZ"", ""CameraAtOffsetX"", ""CameraAtOffsetY"", ""CameraAtOffsetZ"", + ""ForceMouselook"", ""ScriptAccessPin"", ""AllowedDrop"", ""DieAtEdge"", ""SalePrice"", ""SaleType"", ""ColorR"", ""ColorG"", ""ColorB"", ""ColorA"", + ""ParticleSystem"", ""ClickAction"", ""Material"", ""CollisionSound"", ""CollisionSoundVolume"", ""PassTouches"", ""LinkNumber"", ""MediaURL"", ""DynAttrs"", + ""PhysicsShapeType"", ""Density"", ""GravityModifier"", ""Friction"", ""Restitution"" + ) Select + :UUID, :CreationDate, :Name, :Text, :Description, :SitName, :TouchName, :ObjectFlags, :OwnerMask, :NextOwnerMask, :GroupMask, + :EveryoneMask, :BaseMask, :PositionX, :PositionY, :PositionZ, :GroupPositionX, :GroupPositionY, :GroupPositionZ, :VelocityX, + :VelocityY, :VelocityZ, :AngularVelocityX, :AngularVelocityY, :AngularVelocityZ, :AccelerationX, :AccelerationY, :AccelerationZ, + :RotationX, :RotationY, :RotationZ, :RotationW, :SitTargetOffsetX, :SitTargetOffsetY, :SitTargetOffsetZ, :SitTargetOrientW, + :SitTargetOrientX, :SitTargetOrientY, :SitTargetOrientZ, :RegionUUID, :CreatorID, :OwnerID, :GroupID, :LastOwnerID, :SceneGroupID, + :PayPrice, :PayButton1, :PayButton2, :PayButton3, :PayButton4, :LoopedSound, :LoopedSoundGain, :TextureAnimation, :OmegaX, + :OmegaY, :OmegaZ, :CameraEyeOffsetX, :CameraEyeOffsetY, :CameraEyeOffsetZ, :CameraAtOffsetX, :CameraAtOffsetY, :CameraAtOffsetZ, + :ForceMouselook, :ScriptAccessPin, :AllowedDrop, :DieAtEdge, :SalePrice, :SaleType, :ColorR, :ColorG, :ColorB, :ColorA, + :ParticleSystem, :ClickAction, :Material, :CollisionSound, :CollisionSoundVolume, :PassTouches, :LinkNumber, :MediaURL, :DynAttrs, + :PhysicsShapeType, :Density, :GravityModifier, :Friction, :Restitution + where not EXISTS (SELECT ""UUID"" FROM prims WHERE ""UUID"" = :UUID); + "; + + //Set commandtext. + sqlCommand.CommandText = queryPrims; + //Add parameters + sqlCommand.Parameters.AddRange(CreatePrimParameters(sceneObjectPart, sceneGroupID, regionUUID)); + + //Execute the query. If it fails then error is trapped in calling function + sqlCommand.ExecuteNonQuery(); + } + + /// + /// Stores the scene object prim shapes. + /// + /// The sceneobjectpart containing prim shape. + /// The SQL command with the transaction. + /// The scenegroup UUID. + /// The region UUID. + private void StoreSceneObjectPrimShapes(SceneObjectPart sceneObjectPart, NpgsqlCommand sqlCommand, UUID sceneGroupID, UUID regionUUID) + { + //Big query to or insert or update primshapes + + string queryPrimShapes = @" + UPDATE primshapes SET + ""Shape"" = :Shape, ""ScaleX"" = :ScaleX, ""ScaleY"" = :ScaleY, ""ScaleZ"" = :ScaleZ, ""PCode"" = :PCode, ""PathBegin"" = :PathBegin, + ""PathEnd"" = :PathEnd, ""PathScaleX"" = :PathScaleX, ""PathScaleY"" = :PathScaleY, ""PathShearX"" = :PathShearX, ""PathShearY"" = :PathShearY, + ""PathSkew"" = :PathSkew, ""PathCurve"" = :PathCurve, ""PathRadiusOffset"" = :PathRadiusOffset, ""PathRevolutions"" = :PathRevolutions, + ""PathTaperX"" = :PathTaperX, ""PathTaperY"" = :PathTaperY, ""PathTwist"" = :PathTwist, ""PathTwistBegin"" = :PathTwistBegin, + ""ProfileBegin"" = :ProfileBegin, ""ProfileEnd"" = :ProfileEnd, ""ProfileCurve"" = :ProfileCurve, ""ProfileHollow"" = :ProfileHollow, + ""Texture"" = :Texture, ""ExtraParams"" = :ExtraParams, ""State"" = :State, ""Media"" = :Media + WHERE ""UUID"" = :UUID ; + + INSERT INTO + primshapes ( + ""UUID"", ""Shape"", ""ScaleX"", ""ScaleY"", ""ScaleZ"", ""PCode"", ""PathBegin"", ""PathEnd"", ""PathScaleX"", ""PathScaleY"", ""PathShearX"", ""PathShearY"", + ""PathSkew"", ""PathCurve"", ""PathRadiusOffset"", ""PathRevolutions"", ""PathTaperX"", ""PathTaperY"", ""PathTwist"", ""PathTwistBegin"", ""ProfileBegin"", + ""ProfileEnd"", ""ProfileCurve"", ""ProfileHollow"", ""Texture"", ""ExtraParams"", ""State"", ""Media"" + ) + Select + :UUID, :Shape, :ScaleX, :ScaleY, :ScaleZ, :PCode, :PathBegin, :PathEnd, :PathScaleX, :PathScaleY, :PathShearX, :PathShearY, + :PathSkew, :PathCurve, :PathRadiusOffset, :PathRevolutions, :PathTaperX, :PathTaperY, :PathTwist, :PathTwistBegin, :ProfileBegin, + :ProfileEnd, :ProfileCurve, :ProfileHollow, :Texture, :ExtraParams, :State, :Media + where not EXISTS (SELECT ""UUID"" FROM primshapes WHERE ""UUID"" = :UUID); + "; + + //Set commandtext. + sqlCommand.CommandText = queryPrimShapes; + + //Add parameters + sqlCommand.Parameters.AddRange(CreatePrimShapeParameters(sceneObjectPart, sceneGroupID, regionUUID)); + + //Execute the query. If it fails then error is trapped in calling function + sqlCommand.ExecuteNonQuery(); + + } + + /// + /// Removes a object from the database. + /// Meaning removing it from tables Prims, PrimShapes and PrimItems + /// + /// id of scenegroup + /// regionUUID (is this used anyway + public void RemoveObject(UUID objectID, UUID regionUUID) + { + //_Log.InfoFormat("[PGSQL]: Removing obj: {0} from region: {1}", objectID, regionUUID); + + //Remove from prims and primsitem table + string sqlPrims = @"DELETE FROM PRIMS WHERE ""SceneGroupID"" = :objectID"; + string sqlPrimItems = @"DELETE FROM PRIMITEMS WHERE ""primID"" in (SELECT ""UUID"" FROM PRIMS WHERE ""SceneGroupID"" = :objectID)"; + string sqlPrimShapes = @"DELETE FROM PRIMSHAPES WHERE ""UUID"" in (SELECT ""UUID"" FROM PRIMS WHERE ""SceneGroupID"" = :objectID)"; + + lock (_Database) + { + //Using the non transaction mode. + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + cmd.Connection = conn; + cmd.CommandText = sqlPrimShapes; + conn.Open(); + cmd.Parameters.Add(_Database.CreateParameter("objectID", objectID)); + cmd.ExecuteNonQuery(); + + cmd.CommandText = sqlPrimItems; + cmd.ExecuteNonQuery(); + + cmd.CommandText = sqlPrims; + cmd.ExecuteNonQuery(); + } + } + } + + /// + /// Store the inventory of a prim. Warning deletes everything first and then adds all again. + /// + /// + /// + public void StorePrimInventory(UUID primID, ICollection items) + { + //_Log.InfoFormat("[REGION DB: Persisting Prim Inventory with prim ID {0}", primID); + + //Statement from PGSQL section! + // 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. + + //Delete everything from PrimID + //TODO add index on PrimID in DB, if not already exist + + string sql = @"delete from primitems where ""primID"" = :primID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("primID", primID)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + + sql = + @"INSERT INTO primitems ( + ""itemID"",""primID"",""assetID"",""parentFolderID"",""invType"",""assetType"",""name"",""description"",""creationDate"",""creatorID"",""ownerID"",""lastOwnerID"",""groupID"", + ""nextPermissions"",""currentPermissions"",""basePermissions"",""everyonePermissions"",""groupPermissions"",""flags"") + VALUES (:itemID,:primID,:assetID,:parentFolderID,:invType,:assetType,:name,:description,:creationDate,:creatorID,:ownerID, + :lastOwnerID,:groupID,:nextPermissions,:currentPermissions,:basePermissions,:everyonePermissions,:groupPermissions,:flags)"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + conn.Open(); + foreach (TaskInventoryItem taskItem in items) + { + cmd.Parameters.AddRange(CreatePrimInventoryParameters(taskItem)); + cmd.ExecuteNonQuery(); + cmd.Parameters.Clear(); + } + } + } + + #endregion + + /// + /// Loads the terrain map. + /// + /// regionID. + /// + public double[,] LoadTerrain(UUID regionID) + { + double[,] terrain = new double[(int)Constants.RegionSize, (int)Constants.RegionSize]; + terrain.Initialize(); + + string sql = @"select ""RegionUUID"", ""Revision"", ""Heightfield"" from terrain + where ""RegionUUID"" = :RegionUUID order by ""Revision"" desc limit 1; "; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + // PGSqlParameter param = new PGSqlParameter(); + cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionID)); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + int rev; + if (reader.Read()) + { + MemoryStream str = new MemoryStream((byte[])reader["Heightfield"]); + BinaryReader br = new BinaryReader(str); + for (int x = 0; x < (int)Constants.RegionSize; x++) + { + for (int y = 0; y < (int)Constants.RegionSize; y++) + { + terrain[x, y] = br.ReadDouble(); + } + } + rev = (int)reader["Revision"]; + } + else + { + _Log.Info("[REGION DB]: No terrain found for region"); + return null; + } + _Log.Info("[REGION DB]: Loaded terrain revision r" + rev); + } + } + + return terrain; + } + + /// + /// Stores the terrain map to DB. + /// + /// terrain map data. + /// regionID. + public void StoreTerrain(double[,] terrain, UUID regionID) + { + int revision = Util.UnixTimeSinceEpoch(); + + //Delete old terrain map + string sql = @"delete from terrain where ""RegionUUID""=:RegionUUID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionID)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + + _Log.Info("[REGION DB]: Deleted terrain revision r " + revision); + + sql = @"insert into terrain(""RegionUUID"", ""Revision"", ""Heightfield"") values(:RegionUUID, :Revision, :Heightfield)"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionID)); + cmd.Parameters.Add(_Database.CreateParameter("Revision", revision)); + cmd.Parameters.Add(_Database.CreateParameter("Heightfield", serializeTerrain(terrain))); + conn.Open(); + cmd.ExecuteNonQuery(); + } + + _Log.Info("[REGION DB]: Stored terrain revision r " + revision); + } + + /// + /// Loads all the land objects of a region. + /// + /// The region UUID. + /// + public List LoadLandObjects(UUID regionUUID) + { + List LandDataForRegion = new List(); + + string sql = @"select * from land where ""RegionUUID"" = :RegionUUID"; + + //Retrieve all land data from region + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionUUID)); + conn.Open(); + using (NpgsqlDataReader readerLandData = cmd.ExecuteReader()) + { + while (readerLandData.Read()) + { + LandDataForRegion.Add(BuildLandData(readerLandData)); + } + } + } + + //Retrieve all accesslist data for all landdata + foreach (LandData LandData in LandDataForRegion) + { + sql = @"select * from landaccesslist where ""LandUUID"" = :LandUUID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("LandUUID", LandData.GlobalID)); + conn.Open(); + using (NpgsqlDataReader readerAccessList = cmd.ExecuteReader()) + { + while (readerAccessList.Read()) + { + LandData.ParcelAccessList.Add(BuildLandAccessData(readerAccessList)); + } + } + } + } + + //Return data + return LandDataForRegion; + } + + /// + /// Stores land object with landaccess list. + /// + /// parcel data. + public void StoreLandObject(ILandObject parcel) + { + //As this is only one record in land table I just delete all and then add a new record. + //As the delete landaccess is already in the pgsql code + + //Delete old values + RemoveLandObject(parcel.LandData.GlobalID); + + //Insert new values + string sql = @"INSERT INTO land + (""UUID"",""RegionUUID"",""LocalLandID"",""Bitmap"",""Name"",""Description"",""OwnerUUID"",""IsGroupOwned"",""Area"",""AuctionID"",""Category"",""ClaimDate"",""ClaimPrice"", + ""GroupUUID"",""SalePrice"",""LandStatus"",""LandFlags"",""LandingType"",""MediaAutoScale"",""MediaTextureUUID"",""MediaURL"",""MusicURL"",""PassHours"",""PassPrice"", + ""SnapshotUUID"",""UserLocationX"",""UserLocationY"",""UserLocationZ"",""UserLookAtX"",""UserLookAtY"",""UserLookAtZ"",""AuthbuyerID"",""OtherCleanTime"") + VALUES + (:UUID,:RegionUUID,:LocalLandID,:Bitmap,:Name,:Description,:OwnerUUID,:IsGroupOwned,:Area,:AuctionID,:Category,:ClaimDate,:ClaimPrice, + :GroupUUID,:SalePrice,:LandStatus,:LandFlags,:LandingType,:MediaAutoScale,:MediaTextureUUID,:MediaURL,:MusicURL,:PassHours,:PassPrice, + :SnapshotUUID,:UserLocationX,:UserLocationY,:UserLocationZ,:UserLookAtX,:UserLookAtY,:UserLookAtZ,:AuthbuyerID,:OtherCleanTime)"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.AddRange(CreateLandParameters(parcel.LandData, parcel.RegionUUID)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + + sql = @"INSERT INTO landaccesslist (""LandUUID"",""AccessUUID"",""LandFlags"",""Expires"") VALUES (:LandUUID,:AccessUUID,:Flags,:Expires)"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + conn.Open(); + foreach (LandAccessEntry parcelAccessEntry in parcel.LandData.ParcelAccessList) + { + cmd.Parameters.AddRange(CreateLandAccessParameters(parcelAccessEntry, parcel.RegionUUID)); + + cmd.ExecuteNonQuery(); + cmd.Parameters.Clear(); + } + } + } + + /// + /// Removes a land object from DB. + /// + /// UUID of landobject + public void RemoveLandObject(UUID globalID) + { + string sql = @"delete from land where ""UUID""=:UUID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("UUID", globalID)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + sql = @"delete from landaccesslist where ""LandUUID""=:UUID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("UUID", globalID)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + } + public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID) + { + RegionLightShareData nWP = new RegionLightShareData(); + nWP.OnSave += StoreRegionWindlightSettings; + + string sql = @"select * from regionwindlight where ""region_id"" = :regionID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("regionID", regionUUID)); + conn.Open(); + using (NpgsqlDataReader result = cmd.ExecuteReader()) + { + if (!result.Read()) + { + //No result, so store our default windlight profile and return it + nWP.regionID = regionUUID; + StoreRegionWindlightSettings(nWP); + return nWP; + } + else + { + nWP.regionID = DBGuid.FromDB(result["region_id"]); + nWP.waterColor.X = Convert.ToSingle(result["water_color_r"]); + nWP.waterColor.Y = Convert.ToSingle(result["water_color_g"]); + nWP.waterColor.Z = Convert.ToSingle(result["water_color_b"]); + nWP.waterFogDensityExponent = Convert.ToSingle(result["water_fog_density_exponent"]); + nWP.underwaterFogModifier = Convert.ToSingle(result["underwater_fog_modifier"]); + nWP.reflectionWaveletScale.X = Convert.ToSingle(result["reflection_wavelet_scale_1"]); + nWP.reflectionWaveletScale.Y = Convert.ToSingle(result["reflection_wavelet_scale_2"]); + nWP.reflectionWaveletScale.Z = Convert.ToSingle(result["reflection_wavelet_scale_3"]); + nWP.fresnelScale = Convert.ToSingle(result["fresnel_scale"]); + nWP.fresnelOffset = Convert.ToSingle(result["fresnel_offset"]); + nWP.refractScaleAbove = Convert.ToSingle(result["refract_scale_above"]); + nWP.refractScaleBelow = Convert.ToSingle(result["refract_scale_below"]); + nWP.blurMultiplier = Convert.ToSingle(result["blur_multiplier"]); + nWP.bigWaveDirection.X = Convert.ToSingle(result["big_wave_direction_x"]); + nWP.bigWaveDirection.Y = Convert.ToSingle(result["big_wave_direction_y"]); + nWP.littleWaveDirection.X = Convert.ToSingle(result["little_wave_direction_x"]); + nWP.littleWaveDirection.Y = Convert.ToSingle(result["little_wave_direction_y"]); + UUID.TryParse(result["normal_map_texture"].ToString(), out nWP.normalMapTexture); + nWP.horizon.X = Convert.ToSingle(result["horizon_r"]); + nWP.horizon.Y = Convert.ToSingle(result["horizon_g"]); + nWP.horizon.Z = Convert.ToSingle(result["horizon_b"]); + nWP.horizon.W = Convert.ToSingle(result["horizon_i"]); + nWP.hazeHorizon = Convert.ToSingle(result["haze_horizon"]); + nWP.blueDensity.X = Convert.ToSingle(result["blue_density_r"]); + nWP.blueDensity.Y = Convert.ToSingle(result["blue_density_g"]); + nWP.blueDensity.Z = Convert.ToSingle(result["blue_density_b"]); + nWP.blueDensity.W = Convert.ToSingle(result["blue_density_i"]); + nWP.hazeDensity = Convert.ToSingle(result["haze_density"]); + nWP.densityMultiplier = Convert.ToSingle(result["density_multiplier"]); + nWP.distanceMultiplier = Convert.ToSingle(result["distance_multiplier"]); + nWP.maxAltitude = Convert.ToUInt16(result["max_altitude"]); + nWP.sunMoonColor.X = Convert.ToSingle(result["sun_moon_color_r"]); + nWP.sunMoonColor.Y = Convert.ToSingle(result["sun_moon_color_g"]); + nWP.sunMoonColor.Z = Convert.ToSingle(result["sun_moon_color_b"]); + nWP.sunMoonColor.W = Convert.ToSingle(result["sun_moon_color_i"]); + nWP.sunMoonPosition = Convert.ToSingle(result["sun_moon_position"]); + nWP.ambient.X = Convert.ToSingle(result["ambient_r"]); + nWP.ambient.Y = Convert.ToSingle(result["ambient_g"]); + nWP.ambient.Z = Convert.ToSingle(result["ambient_b"]); + nWP.ambient.W = Convert.ToSingle(result["ambient_i"]); + nWP.eastAngle = Convert.ToSingle(result["east_angle"]); + nWP.sunGlowFocus = Convert.ToSingle(result["sun_glow_focus"]); + nWP.sunGlowSize = Convert.ToSingle(result["sun_glow_size"]); + nWP.sceneGamma = Convert.ToSingle(result["scene_gamma"]); + nWP.starBrightness = Convert.ToSingle(result["star_brightness"]); + nWP.cloudColor.X = Convert.ToSingle(result["cloud_color_r"]); + nWP.cloudColor.Y = Convert.ToSingle(result["cloud_color_g"]); + nWP.cloudColor.Z = Convert.ToSingle(result["cloud_color_b"]); + nWP.cloudColor.W = Convert.ToSingle(result["cloud_color_i"]); + nWP.cloudXYDensity.X = Convert.ToSingle(result["cloud_x"]); + nWP.cloudXYDensity.Y = Convert.ToSingle(result["cloud_y"]); + nWP.cloudXYDensity.Z = Convert.ToSingle(result["cloud_density"]); + nWP.cloudCoverage = Convert.ToSingle(result["cloud_coverage"]); + nWP.cloudScale = Convert.ToSingle(result["cloud_scale"]); + nWP.cloudDetailXYDensity.X = Convert.ToSingle(result["cloud_detail_x"]); + nWP.cloudDetailXYDensity.Y = Convert.ToSingle(result["cloud_detail_y"]); + nWP.cloudDetailXYDensity.Z = Convert.ToSingle(result["cloud_detail_density"]); + nWP.cloudScrollX = Convert.ToSingle(result["cloud_scroll_x"]); + nWP.cloudScrollXLock = Convert.ToBoolean(result["cloud_scroll_x_lock"]); + nWP.cloudScrollY = Convert.ToSingle(result["cloud_scroll_y"]); + nWP.cloudScrollYLock = Convert.ToBoolean(result["cloud_scroll_y_lock"]); + nWP.drawClassicClouds = Convert.ToBoolean(result["draw_classic_clouds"]); + nWP.valid = true; + } + } + } + return nWP; + } + + public void RemoveRegionWindlightSettings(UUID regionID) + { + string sql = @"delete from regionwindlight where ""region_id"" = :region_id"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + conn.Open(); + cmd.Parameters.Add(_Database.CreateParameter("region_id", regionID)); + cmd.ExecuteNonQuery(); + } + } + + public void StoreRegionWindlightSettings(RegionLightShareData wl) + { + string sql = @"select count (region_id) from regionwindlight where ""region_id"" = :region_id ;"; + bool exists = false; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("region_id", wl.regionID)); + exists = (int)cmd.ExecuteScalar() > 0; + } + } + if (exists) + { + RemoveRegionWindlightSettings(wl.regionID); + } + + // sql insert + sql = @"INSERT INTO regionwindlight + (region_id + ,water_color_r + ,water_color_g + ,water_color_b + ,water_fog_density_exponent + ,underwater_fog_modifier + ,reflection_wavelet_scale_1 + ,reflection_wavelet_scale_2 + ,reflection_wavelet_scale_3 + ,fresnel_scale + ,fresnel_offset + ,refract_scale_above + ,refract_scale_below + ,blur_multiplier + ,big_wave_direction_x + ,big_wave_direction_y + ,little_wave_direction_x + ,little_wave_direction_y + ,normal_map_texture + ,horizon_r + ,horizon_g + ,horizon_b + ,horizon_i + ,haze_horizon + ,blue_density_r + ,blue_density_g + ,blue_density_b + ,blue_density_i + ,haze_density + ,density_multiplier + ,distance_multiplier + ,max_altitude + ,sun_moon_color_r + ,sun_moon_color_g + ,sun_moon_color_b + ,sun_moon_color_i + ,sun_moon_position + ,ambient_r + ,ambient_g + ,ambient_b + ,ambient_i + ,east_angle + ,sun_glow_focus + ,sun_glow_size + ,scene_gamma + ,star_brightness + ,cloud_color_r + ,cloud_color_g + ,cloud_color_b + ,cloud_color_i + ,cloud_x + ,cloud_y + ,cloud_density + ,cloud_coverage + ,cloud_scale + ,cloud_detail_x + ,cloud_detail_y + ,cloud_detail_density + ,cloud_scroll_x + ,cloud_scroll_x_lock + ,cloud_scroll_y + ,cloud_scroll_y_lock + ,draw_classic_clouds) + VALUES + (:region_id + ,:water_color_r + ,:water_color_g + ,:water_color_b + ,:water_fog_density_exponent + ,:underwater_fog_modifier + ,:reflection_wavelet_scale_1 + ,:reflection_wavelet_scale_2 + ,:reflection_wavelet_scale_3 + ,:fresnel_scale + ,:fresnel_offset + ,:refract_scale_above + ,:refract_scale_below + ,:blur_multiplier + ,:big_wave_direction_x + ,:big_wave_direction_y + ,:little_wave_direction_x + ,:little_wave_direction_y + ,:normal_map_texture + ,:horizon_r + ,:horizon_g + ,:horizon_b + ,:horizon_i + ,:haze_horizon + ,:blue_density_r + ,:blue_density_g + ,:blue_density_b + ,:blue_density_i + ,:haze_density + ,:density_multiplier + ,:distance_multiplier + ,:max_altitude + ,:sun_moon_color_r + ,:sun_moon_color_g + ,:sun_moon_color_b + ,:sun_moon_color_i + ,:sun_moon_position + ,:ambient_r + ,:ambient_g + ,:ambient_b + ,:ambient_i + ,:east_angle + ,:sun_glow_focus + ,:sun_glow_size + ,:scene_gamma + ,:star_brightness + ,:cloud_color_r + ,:cloud_color_g + ,:cloud_color_b + ,:cloud_color_i + ,:cloud_x + ,:cloud_y + ,:cloud_density + ,:cloud_coverage + ,:cloud_scale + ,:cloud_detail_x + ,:cloud_detail_y + ,:cloud_detail_density + ,:cloud_scroll_x + ,:cloud_scroll_x_lock + ,:cloud_scroll_y + ,:cloud_scroll_y_lock + ,:draw_classic_clouds);"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + { + conn.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("region_id", wl.regionID)); + cmd.Parameters.Add(_Database.CreateParameter("water_color_r", wl.waterColor.X)); + cmd.Parameters.Add(_Database.CreateParameter("water_color_g", wl.waterColor.Y)); + cmd.Parameters.Add(_Database.CreateParameter("water_color_b", wl.waterColor.Z)); + cmd.Parameters.Add(_Database.CreateParameter("water_fog_density_exponent", wl.waterFogDensityExponent)); + cmd.Parameters.Add(_Database.CreateParameter("underwater_fog_modifier", wl.underwaterFogModifier)); + cmd.Parameters.Add(_Database.CreateParameter("reflection_wavelet_scale_1", wl.reflectionWaveletScale.X)); + cmd.Parameters.Add(_Database.CreateParameter("reflection_wavelet_scale_2", wl.reflectionWaveletScale.Y)); + cmd.Parameters.Add(_Database.CreateParameter("reflection_wavelet_scale_3", wl.reflectionWaveletScale.Z)); + cmd.Parameters.Add(_Database.CreateParameter("fresnel_scale", wl.fresnelScale)); + cmd.Parameters.Add(_Database.CreateParameter("fresnel_offset", wl.fresnelOffset)); + cmd.Parameters.Add(_Database.CreateParameter("refract_scale_above", wl.refractScaleAbove)); + cmd.Parameters.Add(_Database.CreateParameter("refract_scale_below", wl.refractScaleBelow)); + cmd.Parameters.Add(_Database.CreateParameter("blur_multiplier", wl.blurMultiplier)); + cmd.Parameters.Add(_Database.CreateParameter("big_wave_direction_x", wl.bigWaveDirection.X)); + cmd.Parameters.Add(_Database.CreateParameter("big_wave_direction_y", wl.bigWaveDirection.Y)); + cmd.Parameters.Add(_Database.CreateParameter("little_wave_direction_x", wl.littleWaveDirection.X)); + cmd.Parameters.Add(_Database.CreateParameter("little_wave_direction_y", wl.littleWaveDirection.Y)); + cmd.Parameters.Add(_Database.CreateParameter("normal_map_texture", wl.normalMapTexture)); + cmd.Parameters.Add(_Database.CreateParameter("horizon_r", wl.horizon.X)); + cmd.Parameters.Add(_Database.CreateParameter("horizon_g", wl.horizon.Y)); + cmd.Parameters.Add(_Database.CreateParameter("horizon_b", wl.horizon.Z)); + cmd.Parameters.Add(_Database.CreateParameter("horizon_i", wl.horizon.W)); + cmd.Parameters.Add(_Database.CreateParameter("haze_horizon", wl.hazeHorizon)); + cmd.Parameters.Add(_Database.CreateParameter("blue_density_r", wl.blueDensity.X)); + cmd.Parameters.Add(_Database.CreateParameter("blue_density_g", wl.blueDensity.Y)); + cmd.Parameters.Add(_Database.CreateParameter("blue_density_b", wl.blueDensity.Z)); + cmd.Parameters.Add(_Database.CreateParameter("blue_density_i", wl.blueDensity.W)); + cmd.Parameters.Add(_Database.CreateParameter("haze_density", wl.hazeDensity)); + cmd.Parameters.Add(_Database.CreateParameter("density_multiplier", wl.densityMultiplier)); + cmd.Parameters.Add(_Database.CreateParameter("distance_multiplier", wl.distanceMultiplier)); + cmd.Parameters.Add(_Database.CreateParameter("max_altitude", wl.maxAltitude)); + cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_r", wl.sunMoonColor.X)); + cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_g", wl.sunMoonColor.Y)); + cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_b", wl.sunMoonColor.Z)); + cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_i", wl.sunMoonColor.W)); + cmd.Parameters.Add(_Database.CreateParameter("sun_moon_position", wl.sunMoonPosition)); + cmd.Parameters.Add(_Database.CreateParameter("ambient_r", wl.ambient.X)); + cmd.Parameters.Add(_Database.CreateParameter("ambient_g", wl.ambient.Y)); + cmd.Parameters.Add(_Database.CreateParameter("ambient_b", wl.ambient.Z)); + cmd.Parameters.Add(_Database.CreateParameter("ambient_i", wl.ambient.W)); + cmd.Parameters.Add(_Database.CreateParameter("east_angle", wl.eastAngle)); + cmd.Parameters.Add(_Database.CreateParameter("sun_glow_focus", wl.sunGlowFocus)); + cmd.Parameters.Add(_Database.CreateParameter("sun_glow_size", wl.sunGlowSize)); + cmd.Parameters.Add(_Database.CreateParameter("scene_gamma", wl.sceneGamma)); + cmd.Parameters.Add(_Database.CreateParameter("star_brightness", wl.starBrightness)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_color_r", wl.cloudColor.X)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_color_g", wl.cloudColor.Y)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_color_b", wl.cloudColor.Z)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_color_i", wl.cloudColor.W)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_x", wl.cloudXYDensity.X)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_y", wl.cloudXYDensity.Y)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_density", wl.cloudXYDensity.Z)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_coverage", wl.cloudCoverage)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_scale", wl.cloudScale)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_detail_x", wl.cloudDetailXYDensity.X)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_detail_y", wl.cloudDetailXYDensity.Y)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_detail_density", wl.cloudDetailXYDensity.Z)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_x", wl.cloudScrollX)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_x_lock", wl.cloudScrollXLock)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_y", wl.cloudScrollY)); + cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_y_lock", wl.cloudScrollYLock)); + cmd.Parameters.Add(_Database.CreateParameter("draw_classic_clouds", wl.drawClassicClouds)); + + cmd.ExecuteNonQuery(); + } + } + #region update + // } + // else + // { + // // sql update + // sql = @"UPDATE [OpenSim].[dbo].[regionwindlight] + // SET [region_id] = @region_id + // ,[water_color_r] = @water_color_r + // ,[water_color_g] = @water_color_g + // ,[water_color_b] = @water_color_b + // ,[water_fog_density_exponent] = @water_fog_density_exponent + // ,[underwater_fog_modifier] = @underwater_fog_modifier + // ,[reflection_wavelet_scale_1] = @reflection_wavelet_scale_1 + // ,[reflection_wavelet_scale_2] = @reflection_wavelet_scale_2 + // ,[reflection_wavelet_scale_3] = @reflection_wavelet_scale_3 + // ,[fresnel_scale] = @fresnel_scale + // ,[fresnel_offset] = @fresnel_offset + // ,[refract_scale_above] = @refract_scale_above + // ,[refract_scale_below] = @refract_scale_below + // ,[blur_multiplier] = @blur_multiplier + // ,[big_wave_direction_x] = @big_wave_direction_x + // ,[big_wave_direction_y] = @big_wave_direction_y + // ,[little_wave_direction_x] = @little_wave_direction_x + // ,[little_wave_direction_y] = @little_wave_direction_y + // ,[normal_map_texture] = @normal_map_texture + // ,[horizon_r] = @horizon_r + // ,[horizon_g] = @horizon_g + // ,[horizon_b] = @horizon_b + // ,[horizon_i] = @horizon_i + // ,[haze_horizon] = @haze_horizon + // ,[blue_density_r] = @blue_density_r + // ,[blue_density_g] = @blue_density_g + // ,[blue_density_b] = @blue_density_b + // ,[blue_density_i] = @blue_density_i + // ,[haze_density] = @haze_density + // ,[density_multiplier] = @density_multiplier + // ,[distance_multiplier] = @distance_multiplier + // ,[max_altitude] = @max_altitude + // ,[sun_moon_color_r] = @sun_moon_color_r + // ,[sun_moon_color_g] = @sun_moon_color_g + // ,[sun_moon_color_b] = @sun_moon_color_b + // ,[sun_moon_color_i] = @sun_moon_color_i + // ,[sun_moon_position] = @sun_moon_position + // ,[ambient_r] = @ambient_r + // ,[ambient_g] = @ambient_g + // ,[ambient_b] = @ambient_b + // ,[ambient_i] = @ambient_i + // ,[east_angle] = @east_angle + // ,[sun_glow_focus] = @sun_glow_focus + // ,[sun_glow_size] = @sun_glow_size + // ,[scene_gamma] = @scene_gamma + // ,[star_brightness] = @star_brightness + // ,[cloud_color_r] = @cloud_color_r + // ,[cloud_color_g] = @cloud_color_g + // ,[cloud_color_b] = @cloud_color_b + // ,[cloud_color_i] = @cloud_color_i + // ,[cloud_x] = @cloud_x + // ,[cloud_y] = @cloud_y + // ,[cloud_density] = @cloud_density + // ,[cloud_coverage] = @cloud_coverage + // ,[cloud_scale] = @cloud_scale + // ,[cloud_detail_x] = @cloud_detail_x + // ,[cloud_detail_y] = @cloud_detail_y + // ,[cloud_detail_density] = @cloud_detail_density + // ,[cloud_scroll_x] = @cloud_scroll_x + // ,[cloud_scroll_x_lock] = @cloud_scroll_x_lock + // ,[cloud_scroll_y] = @cloud_scroll_y + // ,[cloud_scroll_y_lock] = @cloud_scroll_y_lock + // ,[draw_classic_clouds] = @draw_classic_clouds + // WHERE region_id = @region_id"; + // using (SqlConnection conn = new SqlConnection(m_connectionString)) + // { + // conn.Open(); + // using (SqlCommand cmd = new SqlCommand(sql, conn)) + // { + // cmd.Parameters.AddWithValue("region_id", wl.regionID); + // cmd.Parameters.AddWithValue("water_color_r", wl.waterColor.X); + // cmd.Parameters.AddWithValue("water_color_g", wl.waterColor.Y); + // cmd.Parameters.AddWithValue("water_color_b", wl.waterColor.Z); + // cmd.Parameters.AddWithValue("water_fog_density_exponent", wl.waterFogDensityExponent); + // cmd.Parameters.AddWithValue("underwater_fog_modifier", wl.underwaterFogModifier); + // cmd.Parameters.AddWithValue("reflection_wavelet_scale_1", wl.reflectionWaveletScale.X); + // cmd.Parameters.AddWithValue("reflection_wavelet_scale_2", wl.reflectionWaveletScale.Y); + // cmd.Parameters.AddWithValue("reflection_wavelet_scale_3", wl.reflectionWaveletScale.Z); + // cmd.Parameters.AddWithValue("fresnel_scale", wl.fresnelScale); + // cmd.Parameters.AddWithValue("fresnel_offset", wl.fresnelOffset); + // cmd.Parameters.AddWithValue("refract_scale_above", wl.refractScaleAbove); + // cmd.Parameters.AddWithValue("refract_scale_below", wl.refractScaleBelow); + // cmd.Parameters.AddWithValue("blur_multiplier", wl.blurMultiplier); + // cmd.Parameters.AddWithValue("big_wave_direction_x", wl.bigWaveDirection.X); + // cmd.Parameters.AddWithValue("big_wave_direction_y", wl.bigWaveDirection.Y); + // cmd.Parameters.AddWithValue("little_wave_direction_x", wl.littleWaveDirection.X); + // cmd.Parameters.AddWithValue("little_wave_direction_y", wl.littleWaveDirection.Y); + // cmd.Parameters.AddWithValue("normal_map_texture", wl.normalMapTexture); + // cmd.Parameters.AddWithValue("horizon_r", wl.horizon.X); + // cmd.Parameters.AddWithValue("horizon_g", wl.horizon.Y); + // cmd.Parameters.AddWithValue("horizon_b", wl.horizon.Z); + // cmd.Parameters.AddWithValue("horizon_i", wl.horizon.W); + // cmd.Parameters.AddWithValue("haze_horizon", wl.hazeHorizon); + // cmd.Parameters.AddWithValue("blue_density_r", wl.blueDensity.X); + // cmd.Parameters.AddWithValue("blue_density_g", wl.blueDensity.Y); + // cmd.Parameters.AddWithValue("blue_density_b", wl.blueDensity.Z); + // cmd.Parameters.AddWithValue("blue_density_i", wl.blueDensity.W); + // cmd.Parameters.AddWithValue("haze_density", wl.hazeDensity); + // cmd.Parameters.AddWithValue("density_multiplier", wl.densityMultiplier); + // cmd.Parameters.AddWithValue("distance_multiplier", wl.distanceMultiplier); + // cmd.Parameters.AddWithValue("max_altitude", wl.maxAltitude); + // cmd.Parameters.AddWithValue("sun_moon_color_r", wl.sunMoonColor.X); + // cmd.Parameters.AddWithValue("sun_moon_color_g", wl.sunMoonColor.Y); + // cmd.Parameters.AddWithValue("sun_moon_color_b", wl.sunMoonColor.Z); + // cmd.Parameters.AddWithValue("sun_moon_color_i", wl.sunMoonColor.W); + // cmd.Parameters.AddWithValue("sun_moon_position", wl.sunMoonPosition); + // cmd.Parameters.AddWithValue("ambient_r", wl.ambient.X); + // cmd.Parameters.AddWithValue("ambient_g", wl.ambient.Y); + // cmd.Parameters.AddWithValue("ambient_b", wl.ambient.Z); + // cmd.Parameters.AddWithValue("ambient_i", wl.ambient.W); + // cmd.Parameters.AddWithValue("east_angle", wl.eastAngle); + // cmd.Parameters.AddWithValue("sun_glow_focus", wl.sunGlowFocus); + // cmd.Parameters.AddWithValue("sun_glow_size", wl.sunGlowSize); + // cmd.Parameters.AddWithValue("scene_gamma", wl.sceneGamma); + // cmd.Parameters.AddWithValue("star_brightness", wl.starBrightness); + // cmd.Parameters.AddWithValue("cloud_color_r", wl.cloudColor.X); + // cmd.Parameters.AddWithValue("cloud_color_g", wl.cloudColor.Y); + // cmd.Parameters.AddWithValue("cloud_color_b", wl.cloudColor.Z); + // cmd.Parameters.AddWithValue("cloud_color_i", wl.cloudColor.W); + // cmd.Parameters.AddWithValue("cloud_x", wl.cloudXYDensity.X); + // cmd.Parameters.AddWithValue("cloud_y", wl.cloudXYDensity.Y); + // cmd.Parameters.AddWithValue("cloud_density", wl.cloudXYDensity.Z); + // cmd.Parameters.AddWithValue("cloud_coverage", wl.cloudCoverage); + // cmd.Parameters.AddWithValue("cloud_scale", wl.cloudScale); + // cmd.Parameters.AddWithValue("cloud_detail_x", wl.cloudDetailXYDensity.X); + // cmd.Parameters.AddWithValue("cloud_detail_y", wl.cloudDetailXYDensity.Y); + // cmd.Parameters.AddWithValue("cloud_detail_density", wl.cloudDetailXYDensity.Z); + // cmd.Parameters.AddWithValue("cloud_scroll_x", wl.cloudScrollX); + // cmd.Parameters.AddWithValue("cloud_scroll_x_lock", wl.cloudScrollXLock); + // cmd.Parameters.AddWithValue("cloud_scroll_y", wl.cloudScrollY); + // cmd.Parameters.AddWithValue("cloud_scroll_y_lock", wl.cloudScrollYLock); + // cmd.Parameters.AddWithValue("draw_classic_clouds", wl.drawClassicClouds); + + // cmd.ExecuteNonQuery(); + // } + // } + // } + #endregion + } + + #region Environment Settings + public string LoadRegionEnvironmentSettings(UUID regionUUID) + { + string sql = "select * from regionenvironment where region_id = :region_id"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("region_id", regionUUID)); + conn.Open(); + using (NpgsqlDataReader result = cmd.ExecuteReader()) + { + if (!result.Read()) + { + return String.Empty; + } + else + { + return Convert.ToString(result["llsd_settings"]); + } + } + } + } + + public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings) + { + { + string sql = "DELETE FROM regionenvironment WHERE region_id = :region_id ;"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("region_id", regionUUID)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + + sql = "INSERT INTO regionenvironment (region_id, llsd_settings) VALUES (:region_id, :llsd_settings) ;"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("region_id", regionUUID)); + cmd.Parameters.Add(_Database.CreateParameter("llsd_settings", settings)); + + conn.Open(); + cmd.ExecuteNonQuery(); + } + } + } + + public void RemoveRegionEnvironmentSettings(UUID regionUUID) + { + string sql = "delete from regionenvironment where region_id = :region_id ;"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("region_id", regionUUID)); + + conn.Open(); + cmd.ExecuteNonQuery(); + } + } + #endregion + + /// + /// Loads the settings of a region. + /// + /// The region UUID. + /// + public RegionSettings LoadRegionSettings(UUID regionUUID) + { + string sql = @"select * from regionsettings where ""regionUUID"" = :regionUUID"; + RegionSettings regionSettings; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("regionUUID", regionUUID)); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if (reader.Read()) + { + regionSettings = BuildRegionSettings(reader); + regionSettings.OnSave += StoreRegionSettings; + + return regionSettings; + } + } + } + + //If we reach this point then there are new region settings for that region + regionSettings = new RegionSettings(); + regionSettings.RegionUUID = regionUUID; + regionSettings.OnSave += StoreRegionSettings; + + //Store new values + StoreNewRegionSettings(regionSettings); + + LoadSpawnPoints(regionSettings); + + return regionSettings; + } + + /// + /// Store region settings, need to check if the check is really necesary. If we can make something for creating new region. + /// + /// region settings. + public void StoreRegionSettings(RegionSettings regionSettings) + { + //Little check if regionUUID already exist in DB + string regionUUID; + string sql = @"SELECT ""regionUUID"" FROM regionsettings WHERE ""regionUUID"" = :regionUUID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("regionUUID", regionSettings.RegionUUID)); + conn.Open(); + regionUUID = cmd.ExecuteScalar().ToString(); + } + + if (string.IsNullOrEmpty(regionUUID)) + { + StoreNewRegionSettings(regionSettings); + } + else + { + //This method only updates region settings!!! First call LoadRegionSettings to create new region settings in DB + sql = + @"UPDATE regionsettings SET block_terraform = :block_terraform ,block_fly = :block_fly ,allow_damage = :allow_damage +,restrict_pushing = :restrict_pushing ,allow_land_resell = :allow_land_resell ,allow_land_join_divide = :allow_land_join_divide +,block_show_in_search = :block_show_in_search ,agent_limit = :agent_limit ,object_bonus = :object_bonus ,maturity = :maturity +,disable_scripts = :disable_scripts ,disable_collisions = :disable_collisions ,disable_physics = :disable_physics +,terrain_texture_1 = :terrain_texture_1 ,terrain_texture_2 = :terrain_texture_2 ,terrain_texture_3 = :terrain_texture_3 +,terrain_texture_4 = :terrain_texture_4 ,elevation_1_nw = :elevation_1_nw ,elevation_2_nw = :elevation_2_nw +,elevation_1_ne = :elevation_1_ne ,elevation_2_ne = :elevation_2_ne ,elevation_1_se = :elevation_1_se ,elevation_2_se = :elevation_2_se +,elevation_1_sw = :elevation_1_sw ,elevation_2_sw = :elevation_2_sw ,water_height = :water_height ,terrain_raise_limit = :terrain_raise_limit +,terrain_lower_limit = :terrain_lower_limit ,use_estate_sun = :use_estate_sun ,fixed_sun = :fixed_sun ,sun_position = :sun_position +,covenant = :covenant ,covenant_datetime = :covenant_datetime, sunvectorx = :sunvectorx, sunvectory = :sunvectory, sunvectorz = :sunvectorz, +""Sandbox"" = :Sandbox, loaded_creation_datetime = :loaded_creation_datetime, loaded_creation_id = :loaded_creation_id, ""map_tile_ID"" = :TerrainImageID, +""TelehubObject"" = :telehubobject, ""parcel_tile_ID"" = :ParcelImageID + WHERE ""regionUUID"" = :regionUUID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.AddRange(CreateRegionSettingParameters(regionSettings)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + } + SaveSpawnPoints(regionSettings); + } + + public void Shutdown() + { + //Not used?? + } + + #region Private Methods + + /// + /// Serializes the terrain data for storage in DB. + /// + /// terrain data + /// + private static Array serializeTerrain(double[,] val) + { + MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize) * sizeof(double)); + BinaryWriter bw = new BinaryWriter(str); + + // TODO: COMPATIBILITY - Add byte-order conversions + for (int x = 0; x < (int)Constants.RegionSize; x++) + for (int y = 0; y < (int)Constants.RegionSize; y++) + { + double height = val[x, y]; + if (height == 0.0) + height = double.Epsilon; + + bw.Write(height); + } + + return str.ToArray(); + } + + /// + /// Stores new regionsettings. + /// + /// The region settings. + private void StoreNewRegionSettings(RegionSettings regionSettings) + { + string sql = @"INSERT INTO regionsettings + (""regionUUID"",block_terraform,block_fly,allow_damage,restrict_pushing,allow_land_resell,allow_land_join_divide, + block_show_in_search,agent_limit,object_bonus,maturity,disable_scripts,disable_collisions,disable_physics, + terrain_texture_1,terrain_texture_2,terrain_texture_3,terrain_texture_4,elevation_1_nw,elevation_2_nw,elevation_1_ne, + elevation_2_ne,elevation_1_se,elevation_2_se,elevation_1_sw,elevation_2_sw,water_height,terrain_raise_limit, + terrain_lower_limit,use_estate_sun,fixed_sun,sun_position,covenant,covenant_datetime,sunvectorx, sunvectory, sunvectorz, + ""Sandbox"", loaded_creation_datetime, loaded_creation_id + ) + VALUES + (:regionUUID,:block_terraform,:block_fly,:allow_damage,:restrict_pushing,:allow_land_resell,:allow_land_join_divide, + :block_show_in_search,:agent_limit,:object_bonus,:maturity,:disable_scripts,:disable_collisions,:disable_physics, + :terrain_texture_1,:terrain_texture_2,:terrain_texture_3,:terrain_texture_4,:elevation_1_nw,:elevation_2_nw,:elevation_1_ne, + :elevation_2_ne,:elevation_1_se,:elevation_2_se,:elevation_1_sw,:elevation_2_sw,:water_height,:terrain_raise_limit, + :terrain_lower_limit,:use_estate_sun,:fixed_sun,:sun_position,:covenant, :covenant_datetime, :sunvectorx,:sunvectory, + :sunvectorz, :Sandbox, :loaded_creation_datetime, :loaded_creation_id )"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.AddRange(CreateRegionSettingParameters(regionSettings)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + } + + #region Private DataRecord conversion methods + + /// + /// Builds the region settings from a datarecod. + /// + /// datarecord with regionsettings. + /// + private static RegionSettings BuildRegionSettings(IDataRecord row) + { + //TODO change this is some more generic code so we doesnt have to change it every time a new field is added? + RegionSettings newSettings = new RegionSettings(); + + newSettings.RegionUUID = new UUID((Guid)row["regionUUID"]); + newSettings.BlockTerraform = Convert.ToBoolean(row["block_terraform"]); + newSettings.AllowDamage = Convert.ToBoolean(row["allow_damage"]); + newSettings.BlockFly = Convert.ToBoolean(row["block_fly"]); + newSettings.RestrictPushing = Convert.ToBoolean(row["restrict_pushing"]); + newSettings.AllowLandResell = Convert.ToBoolean(row["allow_land_resell"]); + newSettings.AllowLandJoinDivide = Convert.ToBoolean(row["allow_land_join_divide"]); + newSettings.BlockShowInSearch = Convert.ToBoolean(row["block_show_in_search"]); + newSettings.AgentLimit = Convert.ToInt32(row["agent_limit"]); + newSettings.ObjectBonus = Convert.ToDouble(row["object_bonus"]); + newSettings.Maturity = Convert.ToInt32(row["maturity"]); + newSettings.DisableScripts = Convert.ToBoolean(row["disable_scripts"]); + newSettings.DisableCollisions = Convert.ToBoolean(row["disable_collisions"]); + newSettings.DisablePhysics = Convert.ToBoolean(row["disable_physics"]); + newSettings.TerrainTexture1 = new UUID((Guid)row["terrain_texture_1"]); + newSettings.TerrainTexture2 = new UUID((Guid)row["terrain_texture_2"]); + newSettings.TerrainTexture3 = new UUID((Guid)row["terrain_texture_3"]); + newSettings.TerrainTexture4 = new UUID((Guid)row["terrain_texture_4"]); + newSettings.Elevation1NW = Convert.ToDouble(row["elevation_1_nw"]); + newSettings.Elevation2NW = Convert.ToDouble(row["elevation_2_nw"]); + newSettings.Elevation1NE = Convert.ToDouble(row["elevation_1_ne"]); + newSettings.Elevation2NE = Convert.ToDouble(row["elevation_2_ne"]); + newSettings.Elevation1SE = Convert.ToDouble(row["elevation_1_se"]); + newSettings.Elevation2SE = Convert.ToDouble(row["elevation_2_se"]); + newSettings.Elevation1SW = Convert.ToDouble(row["elevation_1_sw"]); + newSettings.Elevation2SW = Convert.ToDouble(row["elevation_2_sw"]); + newSettings.WaterHeight = Convert.ToDouble(row["water_height"]); + newSettings.TerrainRaiseLimit = Convert.ToDouble(row["terrain_raise_limit"]); + newSettings.TerrainLowerLimit = Convert.ToDouble(row["terrain_lower_limit"]); + newSettings.UseEstateSun = Convert.ToBoolean(row["use_estate_sun"]); + newSettings.Sandbox = Convert.ToBoolean(row["Sandbox"]); + newSettings.FixedSun = Convert.ToBoolean(row["fixed_sun"]); + newSettings.SunPosition = Convert.ToDouble(row["sun_position"]); + newSettings.SunVector = new Vector3( + Convert.ToSingle(row["sunvectorx"]), + Convert.ToSingle(row["sunvectory"]), + Convert.ToSingle(row["sunvectorz"]) + ); + newSettings.Covenant = new UUID((Guid)row["covenant"]); + newSettings.CovenantChangedDateTime = Convert.ToInt32(row["covenant_datetime"]); + newSettings.LoadedCreationDateTime = Convert.ToInt32(row["loaded_creation_datetime"]); + + if (row["loaded_creation_id"] is DBNull) + newSettings.LoadedCreationID = ""; + else + newSettings.LoadedCreationID = (String)row["loaded_creation_id"]; + + newSettings.TerrainImageID = new UUID((string)row["map_tile_ID"]); + newSettings.ParcelImageID = new UUID((Guid)row["parcel_tile_ID"]); + newSettings.TelehubObject = new UUID((Guid)row["TelehubObject"]); + + return newSettings; + } + + /// + /// Builds the land data from a datarecord. + /// + /// datarecord with land data + /// + private static LandData BuildLandData(IDataRecord row) + { + LandData newData = new LandData(); + + newData.GlobalID = new UUID((Guid)row["UUID"]); + newData.LocalID = Convert.ToInt32(row["LocalLandID"]); + + // Bitmap is a byte[512] + newData.Bitmap = (Byte[])row["Bitmap"]; + + newData.Name = (string)row["Name"]; + newData.Description = (string)row["Description"]; + newData.OwnerID = new UUID((Guid)row["OwnerUUID"]); + newData.IsGroupOwned = Convert.ToBoolean(row["IsGroupOwned"]); + newData.Area = Convert.ToInt32(row["Area"]); + newData.AuctionID = Convert.ToUInt32(row["AuctionID"]); //Unemplemented + newData.Category = (ParcelCategory)Convert.ToInt32(row["Category"]); + //Enum libsecondlife.Parcel.ParcelCategory + newData.ClaimDate = Convert.ToInt32(row["ClaimDate"]); + newData.ClaimPrice = Convert.ToInt32(row["ClaimPrice"]); + newData.GroupID = new UUID((Guid)row["GroupUUID"]); + newData.SalePrice = Convert.ToInt32(row["SalePrice"]); + newData.Status = (ParcelStatus)Convert.ToInt32(row["LandStatus"]); + //Enum. libsecondlife.Parcel.ParcelStatus + newData.Flags = Convert.ToUInt32(row["LandFlags"]); + newData.LandingType = Convert.ToByte(row["LandingType"]); + newData.MediaAutoScale = Convert.ToByte(row["MediaAutoScale"]); + newData.MediaID = new UUID((Guid)row["MediaTextureUUID"]); + newData.MediaURL = (string)row["MediaURL"]; + newData.MusicURL = (string)row["MusicURL"]; + newData.PassHours = Convert.ToSingle(row["PassHours"]); + newData.PassPrice = Convert.ToInt32(row["PassPrice"]); + + // UUID authedbuyer; + // UUID snapshotID; + // + // if (UUID.TryParse((string)row["AuthBuyerID"], out authedbuyer)) + // newData.AuthBuyerID = authedbuyer; + // + // if (UUID.TryParse((string)row["SnapshotUUID"], out snapshotID)) + // newData.SnapshotID = snapshotID; + newData.AuthBuyerID = new UUID((Guid)row["AuthBuyerID"]); + newData.SnapshotID = new UUID((Guid)row["SnapshotUUID"]); + + newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]); + + try + { + newData.UserLocation = + new Vector3(Convert.ToSingle(row["UserLocationX"]), Convert.ToSingle(row["UserLocationY"]), + Convert.ToSingle(row["UserLocationZ"])); + newData.UserLookAt = + new Vector3(Convert.ToSingle(row["UserLookAtX"]), Convert.ToSingle(row["UserLookAtY"]), + Convert.ToSingle(row["UserLookAtZ"])); + } + catch (InvalidCastException) + { + newData.UserLocation = Vector3.Zero; + newData.UserLookAt = Vector3.Zero; + _Log.ErrorFormat("[PARCEL]: unable to get parcel telehub settings for {1}", newData.Name); + } + + newData.ParcelAccessList = new List(); + newData.MediaDescription = (string)row["MediaDescription"]; + newData.MediaType = (string)row["MediaType"]; + newData.MediaWidth = Convert.ToInt32((((string)row["MediaSize"]).Split(','))[0]); + newData.MediaHeight = Convert.ToInt32((((string)row["MediaSize"]).Split(','))[1]); + newData.MediaLoop = Convert.ToBoolean(row["MediaLoop"]); + newData.ObscureMusic = Convert.ToBoolean(row["ObscureMusic"]); + newData.ObscureMedia = Convert.ToBoolean(row["ObscureMedia"]); + + return newData; + } + + /// + /// Builds the landaccess data from a data record. + /// + /// datarecord with landaccess data + /// + private static LandAccessEntry BuildLandAccessData(IDataRecord row) + { + LandAccessEntry entry = new LandAccessEntry(); + entry.AgentID = new UUID((Guid)row["AccessUUID"]); + entry.Flags = (AccessList)Convert.ToInt32(row["Flags"]); + entry.Expires = Convert.ToInt32(row["Expires"]); + return entry; + } + + /// + /// Builds the prim from a datarecord. + /// + /// datarecord + /// + private static SceneObjectPart BuildPrim(IDataRecord primRow) + { + SceneObjectPart prim = new SceneObjectPart(); + + prim.UUID = new UUID((Guid)primRow["UUID"]); + // explicit conversion of integers is required, which sort + // of sucks. No idea if there is a shortcut here or not. + prim.CreationDate = Convert.ToInt32(primRow["CreationDate"]); + prim.Name = (string)primRow["Name"]; + // various text fields + prim.Text = (string)primRow["Text"]; + prim.Color = Color.FromArgb(Convert.ToInt32(primRow["ColorA"]), + Convert.ToInt32(primRow["ColorR"]), + Convert.ToInt32(primRow["ColorG"]), + Convert.ToInt32(primRow["ColorB"])); + prim.Description = (string)primRow["Description"]; + prim.SitName = (string)primRow["SitName"]; + prim.TouchName = (string)primRow["TouchName"]; + // permissions + prim.Flags = (PrimFlags)Convert.ToUInt32(primRow["ObjectFlags"]); + //prim.creatorID = new UUID((Guid)primRow["creatorID"]); + prim.CreatorIdentification = (string)primRow["CreatorID"].ToString(); + prim.OwnerID = new UUID((Guid)primRow["OwnerID"]); + prim.GroupID = new UUID((Guid)primRow["GroupID"]); + prim.LastOwnerID = new UUID((Guid)primRow["LastOwnerID"]); + prim.OwnerMask = Convert.ToUInt32(primRow["OwnerMask"]); + prim.NextOwnerMask = Convert.ToUInt32(primRow["NextOwnerMask"]); + prim.GroupMask = Convert.ToUInt32(primRow["GroupMask"]); + prim.EveryoneMask = Convert.ToUInt32(primRow["EveryoneMask"]); + prim.BaseMask = Convert.ToUInt32(primRow["BaseMask"]); + // vectors + prim.OffsetPosition = new Vector3( + Convert.ToSingle(primRow["PositionX"]), + Convert.ToSingle(primRow["PositionY"]), + Convert.ToSingle(primRow["PositionZ"])); + + prim.GroupPosition = new Vector3( + Convert.ToSingle(primRow["GroupPositionX"]), + Convert.ToSingle(primRow["GroupPositionY"]), + Convert.ToSingle(primRow["GroupPositionZ"])); + + prim.Velocity = new Vector3( + Convert.ToSingle(primRow["VelocityX"]), + Convert.ToSingle(primRow["VelocityY"]), + Convert.ToSingle(primRow["VelocityZ"])); + + prim.AngularVelocity = new Vector3( + Convert.ToSingle(primRow["AngularVelocityX"]), + Convert.ToSingle(primRow["AngularVelocityY"]), + Convert.ToSingle(primRow["AngularVelocityZ"])); + + prim.Acceleration = new Vector3( + Convert.ToSingle(primRow["AccelerationX"]), + Convert.ToSingle(primRow["AccelerationY"]), + Convert.ToSingle(primRow["AccelerationZ"])); + + // quaternions + prim.RotationOffset = new Quaternion( + Convert.ToSingle(primRow["RotationX"]), + Convert.ToSingle(primRow["RotationY"]), + Convert.ToSingle(primRow["RotationZ"]), + Convert.ToSingle(primRow["RotationW"])); + + prim.SitTargetPositionLL = new Vector3( + Convert.ToSingle(primRow["SitTargetOffsetX"]), + Convert.ToSingle(primRow["SitTargetOffsetY"]), + Convert.ToSingle(primRow["SitTargetOffsetZ"])); + + prim.SitTargetOrientationLL = new Quaternion( + Convert.ToSingle(primRow["SitTargetOrientX"]), + Convert.ToSingle(primRow["SitTargetOrientY"]), + Convert.ToSingle(primRow["SitTargetOrientZ"]), + Convert.ToSingle(primRow["SitTargetOrientW"])); + + prim.PayPrice[0] = Convert.ToInt32(primRow["PayPrice"]); + prim.PayPrice[1] = Convert.ToInt32(primRow["PayButton1"]); + prim.PayPrice[2] = Convert.ToInt32(primRow["PayButton2"]); + prim.PayPrice[3] = Convert.ToInt32(primRow["PayButton3"]); + prim.PayPrice[4] = Convert.ToInt32(primRow["PayButton4"]); + + prim.Sound = new UUID((Guid)primRow["LoopedSound"]); + prim.SoundGain = Convert.ToSingle(primRow["LoopedSoundGain"]); + prim.SoundFlags = 1; // If it's persisted at all, it's looped + + if (!(primRow["TextureAnimation"] is DBNull)) + prim.TextureAnimation = (Byte[])primRow["TextureAnimation"]; + if (!(primRow["ParticleSystem"] is DBNull)) + prim.ParticleSystem = (Byte[])primRow["ParticleSystem"]; + + prim.AngularVelocity = new Vector3( + Convert.ToSingle(primRow["OmegaX"]), + Convert.ToSingle(primRow["OmegaY"]), + Convert.ToSingle(primRow["OmegaZ"])); + + prim.SetCameraEyeOffset(new Vector3( + Convert.ToSingle(primRow["CameraEyeOffsetX"]), + Convert.ToSingle(primRow["CameraEyeOffsetY"]), + Convert.ToSingle(primRow["CameraEyeOffsetZ"]) + )); + + prim.SetCameraAtOffset(new Vector3( + Convert.ToSingle(primRow["CameraAtOffsetX"]), + Convert.ToSingle(primRow["CameraAtOffsetY"]), + Convert.ToSingle(primRow["CameraAtOffsetZ"]) + )); + + if (Convert.ToInt16(primRow["ForceMouselook"]) != 0) + prim.SetForceMouselook(true); + + prim.ScriptAccessPin = Convert.ToInt32(primRow["ScriptAccessPin"]); + + if (Convert.ToInt16(primRow["AllowedDrop"]) != 0) + prim.AllowedDrop = true; + + if (Convert.ToInt16(primRow["DieAtEdge"]) != 0) + prim.DIE_AT_EDGE = true; + + prim.SalePrice = Convert.ToInt32(primRow["SalePrice"]); + prim.ObjectSaleType = Convert.ToByte(primRow["SaleType"]); + + prim.Material = Convert.ToByte(primRow["Material"]); + + if (!(primRow["ClickAction"] is DBNull)) + prim.ClickAction = Convert.ToByte(primRow["ClickAction"]); + + prim.CollisionSound = new UUID((Guid)primRow["CollisionSound"]); + prim.CollisionSoundVolume = Convert.ToSingle(primRow["CollisionSoundVolume"]); + + prim.PassTouches = (bool)primRow["PassTouches"]; + + if (!(primRow["MediaURL"] is System.DBNull)) + prim.MediaUrl = (string)primRow["MediaURL"]; + + if (!(primRow["DynAttrs"] is System.DBNull) && (string)primRow["DynAttrs"] != "") + prim.DynAttrs = DAMap.FromXml((string)primRow["DynAttrs"]); + else + prim.DynAttrs = new DAMap(); + + prim.PhysicsShapeType = Convert.ToByte(primRow["PhysicsShapeType"]); + prim.Density = Convert.ToSingle(primRow["Density"]); + prim.GravityModifier = Convert.ToSingle(primRow["GravityModifier"]); + prim.Friction = Convert.ToSingle(primRow["Friction"]); + prim.Restitution = Convert.ToSingle(primRow["Restitution"]); + + return prim; + } + + /// + /// Builds the prim shape from a datarecord. + /// + /// The row. + /// + private static PrimitiveBaseShape BuildShape(IDataRecord shapeRow) + { + PrimitiveBaseShape baseShape = new PrimitiveBaseShape(); + + baseShape.Scale = new Vector3( + (float)Convert.ToDouble(shapeRow["ScaleX"]), + (float)Convert.ToDouble(shapeRow["ScaleY"]), + (float)Convert.ToDouble(shapeRow["ScaleZ"])); + + // paths + baseShape.PCode = Convert.ToByte(shapeRow["PCode"]); + baseShape.PathBegin = Convert.ToUInt16(shapeRow["PathBegin"]); + baseShape.PathEnd = Convert.ToUInt16(shapeRow["PathEnd"]); + baseShape.PathScaleX = Convert.ToByte(shapeRow["PathScaleX"]); + baseShape.PathScaleY = Convert.ToByte(shapeRow["PathScaleY"]); + baseShape.PathShearX = Convert.ToByte(shapeRow["PathShearX"]); + baseShape.PathShearY = Convert.ToByte(shapeRow["PathShearY"]); + baseShape.PathSkew = Convert.ToSByte(shapeRow["PathSkew"]); + baseShape.PathCurve = Convert.ToByte(shapeRow["PathCurve"]); + baseShape.PathRadiusOffset = Convert.ToSByte(shapeRow["PathRadiusOffset"]); + baseShape.PathRevolutions = Convert.ToByte(shapeRow["PathRevolutions"]); + baseShape.PathTaperX = Convert.ToSByte(shapeRow["PathTaperX"]); + baseShape.PathTaperY = Convert.ToSByte(shapeRow["PathTaperY"]); + baseShape.PathTwist = Convert.ToSByte(shapeRow["PathTwist"]); + baseShape.PathTwistBegin = Convert.ToSByte(shapeRow["PathTwistBegin"]); + // profile + baseShape.ProfileBegin = Convert.ToUInt16(shapeRow["ProfileBegin"]); + baseShape.ProfileEnd = Convert.ToUInt16(shapeRow["ProfileEnd"]); + baseShape.ProfileCurve = Convert.ToByte(shapeRow["ProfileCurve"]); + baseShape.ProfileHollow = Convert.ToUInt16(shapeRow["ProfileHollow"]); + + byte[] textureEntry = (byte[])shapeRow["Texture"]; + baseShape.TextureEntry = textureEntry; + + baseShape.ExtraParams = (byte[])shapeRow["ExtraParams"]; + + try + { + baseShape.State = Convert.ToByte(shapeRow["State"]); + } + catch (InvalidCastException) + { + } + + if (!(shapeRow["Media"] is System.DBNull)) + { + baseShape.Media = PrimitiveBaseShape.MediaList.FromXml((string)shapeRow["Media"]); + } + + return baseShape; + } + + /// + /// Build a prim inventory item from the persisted data. + /// + /// + /// + private static TaskInventoryItem BuildItem(IDataRecord inventoryRow) + { + TaskInventoryItem taskItem = new TaskInventoryItem(); + + taskItem.ItemID = new UUID((Guid)inventoryRow["itemID"]); + taskItem.ParentPartID = new UUID((Guid)inventoryRow["primID"]); + taskItem.AssetID = new UUID((Guid)inventoryRow["assetID"]); + taskItem.ParentID = new UUID((Guid)inventoryRow["parentFolderID"]); + + taskItem.InvType = Convert.ToInt32(inventoryRow["invType"]); + taskItem.Type = Convert.ToInt32(inventoryRow["assetType"]); + + taskItem.Name = (string)inventoryRow["name"]; + taskItem.Description = (string)inventoryRow["description"]; + taskItem.CreationDate = Convert.ToUInt32(inventoryRow["creationDate"]); + //taskItem.creatorID = new UUID((Guid)inventoryRow["creatorID"]); + taskItem.CreatorIdentification = (string)inventoryRow["creatorID"].ToString(); + taskItem.OwnerID = new UUID((Guid)inventoryRow["ownerID"]); + taskItem.LastOwnerID = new UUID((Guid)inventoryRow["lastOwnerID"]); + taskItem.GroupID = new UUID((Guid)inventoryRow["groupID"]); + + taskItem.NextPermissions = Convert.ToUInt32(inventoryRow["nextPermissions"]); + taskItem.CurrentPermissions = Convert.ToUInt32(inventoryRow["currentPermissions"]); + taskItem.BasePermissions = Convert.ToUInt32(inventoryRow["basePermissions"]); + taskItem.EveryonePermissions = Convert.ToUInt32(inventoryRow["everyonePermissions"]); + taskItem.GroupPermissions = Convert.ToUInt32(inventoryRow["groupPermissions"]); + taskItem.Flags = Convert.ToUInt32(inventoryRow["flags"]); + + return taskItem; + } + + #endregion + + #region Create parameters methods + + /// + /// Creates the prim inventory parameters. + /// + /// item in inventory. + /// + private NpgsqlParameter[] CreatePrimInventoryParameters(TaskInventoryItem taskItem) + { + List parameters = new List(); + + parameters.Add(_Database.CreateParameter("itemID", taskItem.ItemID)); + parameters.Add(_Database.CreateParameter("primID", taskItem.ParentPartID)); + parameters.Add(_Database.CreateParameter("assetID", taskItem.AssetID)); + parameters.Add(_Database.CreateParameter("parentFolderID", taskItem.ParentID)); + parameters.Add(_Database.CreateParameter("invType", taskItem.InvType)); + parameters.Add(_Database.CreateParameter("assetType", taskItem.Type)); + + parameters.Add(_Database.CreateParameter("name", taskItem.Name)); + parameters.Add(_Database.CreateParameter("description", taskItem.Description)); + parameters.Add(_Database.CreateParameter("creationDate", taskItem.CreationDate)); + parameters.Add(_Database.CreateParameter("creatorID", taskItem.CreatorID)); + parameters.Add(_Database.CreateParameter("ownerID", taskItem.OwnerID)); + parameters.Add(_Database.CreateParameter("lastOwnerID", taskItem.LastOwnerID)); + parameters.Add(_Database.CreateParameter("groupID", taskItem.GroupID)); + parameters.Add(_Database.CreateParameter("nextPermissions", taskItem.NextPermissions)); + parameters.Add(_Database.CreateParameter("currentPermissions", taskItem.CurrentPermissions)); + parameters.Add(_Database.CreateParameter("basePermissions", taskItem.BasePermissions)); + parameters.Add(_Database.CreateParameter("everyonePermissions", taskItem.EveryonePermissions)); + parameters.Add(_Database.CreateParameter("groupPermissions", taskItem.GroupPermissions)); + parameters.Add(_Database.CreateParameter("flags", taskItem.Flags)); + + return parameters.ToArray(); + } + + /// + /// Creates the region setting parameters. + /// + /// regionsettings. + /// + private NpgsqlParameter[] CreateRegionSettingParameters(RegionSettings settings) + { + List parameters = new List(); + + parameters.Add(_Database.CreateParameter("regionUUID", settings.RegionUUID)); + parameters.Add(_Database.CreateParameter("block_terraform", settings.BlockTerraform)); + parameters.Add(_Database.CreateParameter("block_fly", settings.BlockFly)); + parameters.Add(_Database.CreateParameter("allow_damage", settings.AllowDamage)); + parameters.Add(_Database.CreateParameter("restrict_pushing", settings.RestrictPushing)); + parameters.Add(_Database.CreateParameter("allow_land_resell", settings.AllowLandResell)); + parameters.Add(_Database.CreateParameter("allow_land_join_divide", settings.AllowLandJoinDivide)); + parameters.Add(_Database.CreateParameter("block_show_in_search", settings.BlockShowInSearch)); + parameters.Add(_Database.CreateParameter("agent_limit", settings.AgentLimit)); + parameters.Add(_Database.CreateParameter("object_bonus", settings.ObjectBonus)); + parameters.Add(_Database.CreateParameter("maturity", settings.Maturity)); + parameters.Add(_Database.CreateParameter("disable_scripts", settings.DisableScripts)); + parameters.Add(_Database.CreateParameter("disable_collisions", settings.DisableCollisions)); + parameters.Add(_Database.CreateParameter("disable_physics", settings.DisablePhysics)); + parameters.Add(_Database.CreateParameter("terrain_texture_1", settings.TerrainTexture1)); + parameters.Add(_Database.CreateParameter("terrain_texture_2", settings.TerrainTexture2)); + parameters.Add(_Database.CreateParameter("terrain_texture_3", settings.TerrainTexture3)); + parameters.Add(_Database.CreateParameter("terrain_texture_4", settings.TerrainTexture4)); + parameters.Add(_Database.CreateParameter("elevation_1_nw", settings.Elevation1NW)); + parameters.Add(_Database.CreateParameter("elevation_2_nw", settings.Elevation2NW)); + parameters.Add(_Database.CreateParameter("elevation_1_ne", settings.Elevation1NE)); + parameters.Add(_Database.CreateParameter("elevation_2_ne", settings.Elevation2NE)); + parameters.Add(_Database.CreateParameter("elevation_1_se", settings.Elevation1SE)); + parameters.Add(_Database.CreateParameter("elevation_2_se", settings.Elevation2SE)); + parameters.Add(_Database.CreateParameter("elevation_1_sw", settings.Elevation1SW)); + parameters.Add(_Database.CreateParameter("elevation_2_sw", settings.Elevation2SW)); + parameters.Add(_Database.CreateParameter("water_height", settings.WaterHeight)); + parameters.Add(_Database.CreateParameter("terrain_raise_limit", settings.TerrainRaiseLimit)); + parameters.Add(_Database.CreateParameter("terrain_lower_limit", settings.TerrainLowerLimit)); + parameters.Add(_Database.CreateParameter("use_estate_sun", settings.UseEstateSun)); + parameters.Add(_Database.CreateParameter("Sandbox", settings.Sandbox)); + parameters.Add(_Database.CreateParameter("fixed_sun", settings.FixedSun)); + parameters.Add(_Database.CreateParameter("sun_position", settings.SunPosition)); + parameters.Add(_Database.CreateParameter("sunvectorx", settings.SunVector.X)); + parameters.Add(_Database.CreateParameter("sunvectory", settings.SunVector.Y)); + parameters.Add(_Database.CreateParameter("sunvectorz", settings.SunVector.Z)); + parameters.Add(_Database.CreateParameter("covenant", settings.Covenant)); + parameters.Add(_Database.CreateParameter("covenant_datetime", settings.CovenantChangedDateTime)); + parameters.Add(_Database.CreateParameter("Loaded_Creation_DateTime", settings.LoadedCreationDateTime)); + parameters.Add(_Database.CreateParameter("Loaded_Creation_ID", settings.LoadedCreationID)); + parameters.Add(_Database.CreateParameter("TerrainImageID", settings.TerrainImageID)); + parameters.Add(_Database.CreateParameter("ParcelImageID", settings.ParcelImageID)); + parameters.Add(_Database.CreateParameter("TelehubObject", settings.TelehubObject)); + + return parameters.ToArray(); + } + + /// + /// Creates the land parameters. + /// + /// land parameters. + /// region UUID. + /// + private NpgsqlParameter[] CreateLandParameters(LandData land, UUID regionUUID) + { + List parameters = new List(); + + parameters.Add(_Database.CreateParameter("UUID", land.GlobalID)); + parameters.Add(_Database.CreateParameter("RegionUUID", regionUUID)); + parameters.Add(_Database.CreateParameter("LocalLandID", land.LocalID)); + + // Bitmap is a byte[512] + parameters.Add(_Database.CreateParameter("Bitmap", land.Bitmap)); + + parameters.Add(_Database.CreateParameter("Name", land.Name)); + parameters.Add(_Database.CreateParameter("Description", land.Description)); + parameters.Add(_Database.CreateParameter("OwnerUUID", land.OwnerID)); + parameters.Add(_Database.CreateParameter("IsGroupOwned", land.IsGroupOwned)); + parameters.Add(_Database.CreateParameter("Area", land.Area)); + parameters.Add(_Database.CreateParameter("AuctionID", land.AuctionID)); //Unemplemented + parameters.Add(_Database.CreateParameter("Category", (int)land.Category)); //Enum libsecondlife.Parcel.ParcelCategory + parameters.Add(_Database.CreateParameter("ClaimDate", land.ClaimDate)); + parameters.Add(_Database.CreateParameter("ClaimPrice", land.ClaimPrice)); + parameters.Add(_Database.CreateParameter("GroupUUID", land.GroupID)); + parameters.Add(_Database.CreateParameter("SalePrice", land.SalePrice)); + parameters.Add(_Database.CreateParameter("LandStatus", (int)land.Status)); //Enum. libsecondlife.Parcel.ParcelStatus + parameters.Add(_Database.CreateParameter("LandFlags", land.Flags)); + parameters.Add(_Database.CreateParameter("LandingType", Convert.ToInt32( land.LandingType) )); + parameters.Add(_Database.CreateParameter("MediaAutoScale", Convert.ToInt32( land.MediaAutoScale ))); + parameters.Add(_Database.CreateParameter("MediaTextureUUID", land.MediaID)); + parameters.Add(_Database.CreateParameter("MediaURL", land.MediaURL)); + parameters.Add(_Database.CreateParameter("MusicURL", land.MusicURL)); + parameters.Add(_Database.CreateParameter("PassHours", land.PassHours)); + parameters.Add(_Database.CreateParameter("PassPrice", land.PassPrice)); + parameters.Add(_Database.CreateParameter("SnapshotUUID", land.SnapshotID)); + parameters.Add(_Database.CreateParameter("UserLocationX", land.UserLocation.X)); + parameters.Add(_Database.CreateParameter("UserLocationY", land.UserLocation.Y)); + parameters.Add(_Database.CreateParameter("UserLocationZ", land.UserLocation.Z)); + parameters.Add(_Database.CreateParameter("UserLookAtX", land.UserLookAt.X)); + parameters.Add(_Database.CreateParameter("UserLookAtY", land.UserLookAt.Y)); + parameters.Add(_Database.CreateParameter("UserLookAtZ", land.UserLookAt.Z)); + parameters.Add(_Database.CreateParameter("AuthBuyerID", land.AuthBuyerID)); + parameters.Add(_Database.CreateParameter("OtherCleanTime", land.OtherCleanTime)); + + return parameters.ToArray(); + } + + /// + /// Creates the land access parameters. + /// + /// parcel access entry. + /// parcel ID. + /// + private NpgsqlParameter[] CreateLandAccessParameters(LandAccessEntry parcelAccessEntry, UUID parcelID) + { + List parameters = new List(); + + parameters.Add(_Database.CreateParameter("LandUUID", parcelID)); + parameters.Add(_Database.CreateParameter("AccessUUID", parcelAccessEntry.AgentID)); + parameters.Add(_Database.CreateParameter("Flags", parcelAccessEntry.Flags)); + parameters.Add(_Database.CreateParameter("Expires", parcelAccessEntry.Expires)); + + return parameters.ToArray(); + } + + /// + /// Creates the prim parameters for storing in DB. + /// + /// Basic data of SceneObjectpart prim. + /// The scenegroup ID. + /// The region ID. + /// + private NpgsqlParameter[] CreatePrimParameters(SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID) + { + List parameters = new List(); + + parameters.Add(_Database.CreateParameter("UUID", prim.UUID)); + parameters.Add(_Database.CreateParameter("RegionUUID", regionUUID)); + parameters.Add(_Database.CreateParameter("CreationDate", prim.CreationDate)); + parameters.Add(_Database.CreateParameter("Name", prim.Name)); + parameters.Add(_Database.CreateParameter("SceneGroupID", sceneGroupID)); + // the UUID of the root part for this SceneObjectGroup + // various text fields + parameters.Add(_Database.CreateParameter("Text", prim.Text)); + parameters.Add(_Database.CreateParameter("ColorR", prim.Color.R)); + parameters.Add(_Database.CreateParameter("ColorG", prim.Color.G)); + parameters.Add(_Database.CreateParameter("ColorB", prim.Color.B)); + parameters.Add(_Database.CreateParameter("ColorA", prim.Color.A)); + parameters.Add(_Database.CreateParameter("Description", prim.Description)); + parameters.Add(_Database.CreateParameter("SitName", prim.SitName)); + parameters.Add(_Database.CreateParameter("TouchName", prim.TouchName)); + // permissions + parameters.Add(_Database.CreateParameter("ObjectFlags", (uint)prim.Flags)); + parameters.Add(_Database.CreateParameter("CreatorID", prim.CreatorID)); + parameters.Add(_Database.CreateParameter("OwnerID", prim.OwnerID)); + parameters.Add(_Database.CreateParameter("GroupID", prim.GroupID)); + parameters.Add(_Database.CreateParameter("LastOwnerID", prim.LastOwnerID)); + parameters.Add(_Database.CreateParameter("OwnerMask", prim.OwnerMask)); + parameters.Add(_Database.CreateParameter("NextOwnerMask", prim.NextOwnerMask)); + parameters.Add(_Database.CreateParameter("GroupMask", prim.GroupMask)); + parameters.Add(_Database.CreateParameter("EveryoneMask", prim.EveryoneMask)); + parameters.Add(_Database.CreateParameter("BaseMask", prim.BaseMask)); + // vectors + parameters.Add(_Database.CreateParameter("PositionX", prim.OffsetPosition.X)); + parameters.Add(_Database.CreateParameter("PositionY", prim.OffsetPosition.Y)); + parameters.Add(_Database.CreateParameter("PositionZ", prim.OffsetPosition.Z)); + parameters.Add(_Database.CreateParameter("GroupPositionX", prim.GroupPosition.X)); + parameters.Add(_Database.CreateParameter("GroupPositionY", prim.GroupPosition.Y)); + parameters.Add(_Database.CreateParameter("GroupPositionZ", prim.GroupPosition.Z)); + parameters.Add(_Database.CreateParameter("VelocityX", prim.Velocity.X)); + parameters.Add(_Database.CreateParameter("VelocityY", prim.Velocity.Y)); + parameters.Add(_Database.CreateParameter("VelocityZ", prim.Velocity.Z)); + parameters.Add(_Database.CreateParameter("AngularVelocityX", prim.AngularVelocity.X)); + parameters.Add(_Database.CreateParameter("AngularVelocityY", prim.AngularVelocity.Y)); + parameters.Add(_Database.CreateParameter("AngularVelocityZ", prim.AngularVelocity.Z)); + parameters.Add(_Database.CreateParameter("AccelerationX", prim.Acceleration.X)); + parameters.Add(_Database.CreateParameter("AccelerationY", prim.Acceleration.Y)); + parameters.Add(_Database.CreateParameter("AccelerationZ", prim.Acceleration.Z)); + // quaternions + parameters.Add(_Database.CreateParameter("RotationX", prim.RotationOffset.X)); + parameters.Add(_Database.CreateParameter("RotationY", prim.RotationOffset.Y)); + parameters.Add(_Database.CreateParameter("RotationZ", prim.RotationOffset.Z)); + parameters.Add(_Database.CreateParameter("RotationW", prim.RotationOffset.W)); + + // Sit target + Vector3 sitTargetPos = prim.SitTargetPositionLL; + parameters.Add(_Database.CreateParameter("SitTargetOffsetX", sitTargetPos.X)); + parameters.Add(_Database.CreateParameter("SitTargetOffsetY", sitTargetPos.Y)); + parameters.Add(_Database.CreateParameter("SitTargetOffsetZ", sitTargetPos.Z)); + + Quaternion sitTargetOrient = prim.SitTargetOrientationLL; + parameters.Add(_Database.CreateParameter("SitTargetOrientW", sitTargetOrient.W)); + parameters.Add(_Database.CreateParameter("SitTargetOrientX", sitTargetOrient.X)); + parameters.Add(_Database.CreateParameter("SitTargetOrientY", sitTargetOrient.Y)); + parameters.Add(_Database.CreateParameter("SitTargetOrientZ", sitTargetOrient.Z)); + + parameters.Add(_Database.CreateParameter("PayPrice", prim.PayPrice[0])); + parameters.Add(_Database.CreateParameter("PayButton1", prim.PayPrice[1])); + parameters.Add(_Database.CreateParameter("PayButton2", prim.PayPrice[2])); + parameters.Add(_Database.CreateParameter("PayButton3", prim.PayPrice[3])); + parameters.Add(_Database.CreateParameter("PayButton4", prim.PayPrice[4])); + + if ((prim.SoundFlags & 1) != 0) // Looped + { + parameters.Add(_Database.CreateParameter("LoopedSound", prim.Sound)); + parameters.Add(_Database.CreateParameter("LoopedSoundGain", prim.SoundGain)); + } + else + { + parameters.Add(_Database.CreateParameter("LoopedSound", UUID.Zero)); + parameters.Add(_Database.CreateParameter("LoopedSoundGain", 0.0f)); + } + + parameters.Add(_Database.CreateParameter("TextureAnimation", prim.TextureAnimation)); + parameters.Add(_Database.CreateParameter("ParticleSystem", prim.ParticleSystem)); + + parameters.Add(_Database.CreateParameter("OmegaX", prim.AngularVelocity.X)); + parameters.Add(_Database.CreateParameter("OmegaY", prim.AngularVelocity.Y)); + parameters.Add(_Database.CreateParameter("OmegaZ", prim.AngularVelocity.Z)); + + parameters.Add(_Database.CreateParameter("CameraEyeOffsetX", prim.GetCameraEyeOffset().X)); + parameters.Add(_Database.CreateParameter("CameraEyeOffsetY", prim.GetCameraEyeOffset().Y)); + parameters.Add(_Database.CreateParameter("CameraEyeOffsetZ", prim.GetCameraEyeOffset().Z)); + + parameters.Add(_Database.CreateParameter("CameraAtOffsetX", prim.GetCameraAtOffset().X)); + parameters.Add(_Database.CreateParameter("CameraAtOffsetY", prim.GetCameraAtOffset().Y)); + parameters.Add(_Database.CreateParameter("CameraAtOffsetZ", prim.GetCameraAtOffset().Z)); + + if (prim.GetForceMouselook()) + parameters.Add(_Database.CreateParameter("ForceMouselook", 1)); + else + parameters.Add(_Database.CreateParameter("ForceMouselook", 0)); + + parameters.Add(_Database.CreateParameter("ScriptAccessPin", prim.ScriptAccessPin)); + + if (prim.AllowedDrop) + parameters.Add(_Database.CreateParameter("AllowedDrop", 1)); + else + parameters.Add(_Database.CreateParameter("AllowedDrop", 0)); + + if (prim.DIE_AT_EDGE) + parameters.Add(_Database.CreateParameter("DieAtEdge", 1)); + else + parameters.Add(_Database.CreateParameter("DieAtEdge", 0)); + + parameters.Add(_Database.CreateParameter("SalePrice", prim.SalePrice)); + parameters.Add(_Database.CreateParameter("SaleType", prim.ObjectSaleType)); + + byte clickAction = prim.ClickAction; + parameters.Add(_Database.CreateParameter("ClickAction", clickAction)); + + parameters.Add(_Database.CreateParameter("Material", prim.Material)); + + parameters.Add(_Database.CreateParameter("CollisionSound", prim.CollisionSound)); + parameters.Add(_Database.CreateParameter("CollisionSoundVolume", prim.CollisionSoundVolume)); + + parameters.Add(_Database.CreateParameter("PassTouches", prim.PassTouches)); + + parameters.Add(_Database.CreateParameter("LinkNumber", prim.LinkNum)); + parameters.Add(_Database.CreateParameter("MediaURL", prim.MediaUrl)); + + if (prim.DynAttrs.CountNamespaces > 0) + parameters.Add(_Database.CreateParameter("DynAttrs", prim.DynAttrs.ToXml())); + else + parameters.Add(_Database.CreateParameter("DynAttrs", null)); + + parameters.Add(_Database.CreateParameter("PhysicsShapeType", prim.PhysicsShapeType)); + parameters.Add(_Database.CreateParameter("Density", (double)prim.Density)); + parameters.Add(_Database.CreateParameter("GravityModifier", (double)prim.GravityModifier)); + parameters.Add(_Database.CreateParameter("Friction", (double)prim.Friction)); + parameters.Add(_Database.CreateParameter("Restitution", (double)prim.Restitution)); + + return parameters.ToArray(); + } + + /// + /// Creates the primshape parameters for stroing in DB. + /// + /// Basic data of SceneObjectpart prim. + /// The scene group ID. + /// The region UUID. + /// + private NpgsqlParameter[] CreatePrimShapeParameters(SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID) + { + List parameters = new List(); + + PrimitiveBaseShape s = prim.Shape; + parameters.Add(_Database.CreateParameter("UUID", prim.UUID)); + // shape is an enum + parameters.Add(_Database.CreateParameter("Shape", 0)); + // vectors + parameters.Add(_Database.CreateParameter("ScaleX", s.Scale.X)); + parameters.Add(_Database.CreateParameter("ScaleY", s.Scale.Y)); + parameters.Add(_Database.CreateParameter("ScaleZ", s.Scale.Z)); + // paths + parameters.Add(_Database.CreateParameter("PCode", s.PCode)); + parameters.Add(_Database.CreateParameter("PathBegin", s.PathBegin)); + parameters.Add(_Database.CreateParameter("PathEnd", s.PathEnd)); + parameters.Add(_Database.CreateParameter("PathScaleX", s.PathScaleX)); + parameters.Add(_Database.CreateParameter("PathScaleY", s.PathScaleY)); + parameters.Add(_Database.CreateParameter("PathShearX", s.PathShearX)); + parameters.Add(_Database.CreateParameter("PathShearY", s.PathShearY)); + parameters.Add(_Database.CreateParameter("PathSkew", s.PathSkew)); + parameters.Add(_Database.CreateParameter("PathCurve", s.PathCurve)); + parameters.Add(_Database.CreateParameter("PathRadiusOffset", s.PathRadiusOffset)); + parameters.Add(_Database.CreateParameter("PathRevolutions", s.PathRevolutions)); + parameters.Add(_Database.CreateParameter("PathTaperX", s.PathTaperX)); + parameters.Add(_Database.CreateParameter("PathTaperY", s.PathTaperY)); + parameters.Add(_Database.CreateParameter("PathTwist", s.PathTwist)); + parameters.Add(_Database.CreateParameter("PathTwistBegin", s.PathTwistBegin)); + // profile + parameters.Add(_Database.CreateParameter("ProfileBegin", s.ProfileBegin)); + parameters.Add(_Database.CreateParameter("ProfileEnd", s.ProfileEnd)); + parameters.Add(_Database.CreateParameter("ProfileCurve", s.ProfileCurve)); + parameters.Add(_Database.CreateParameter("ProfileHollow", s.ProfileHollow)); + parameters.Add(_Database.CreateParameter("Texture", s.TextureEntry)); + parameters.Add(_Database.CreateParameter("ExtraParams", s.ExtraParams)); + parameters.Add(_Database.CreateParameter("State", s.State)); + + if (null == s.Media) + { + parameters.Add(_Database.CreateParameter("Media", DBNull.Value)); + } + else + { + parameters.Add(_Database.CreateParameter("Media", s.Media.ToXml())); + } + + return parameters.ToArray(); + } + + #endregion + + #endregion + + private void LoadSpawnPoints(RegionSettings rs) + { + rs.ClearSpawnPoints(); + + string sql = @"SELECT ""Yaw"", ""Pitch"", ""Distance"" FROM spawn_points WHERE ""RegionUUID"" = :RegionUUID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", rs.RegionUUID)); + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if (reader.Read()) + { + SpawnPoint sp = new SpawnPoint(); + + sp.Yaw = (float)reader["Yaw"]; + sp.Pitch = (float)reader["Pitch"]; + sp.Distance = (float)reader["Distance"]; + + rs.AddSpawnPoint(sp); + } + } + } + } + + private void SaveSpawnPoints(RegionSettings rs) + { + string sql = @"DELETE FROM spawn_points WHERE ""RegionUUID"" = :RegionUUID"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", rs.RegionUUID)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + foreach (SpawnPoint p in rs.SpawnPoints()) + { + sql = @"INSERT INTO spawn_points (""RegionUUID"", ""Yaw"", ""Pitch"", ""Distance"") VALUES (:RegionUUID, :Yaw, :Pitch, :Distance)"; + using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", rs.RegionUUID)); + cmd.Parameters.Add(_Database.CreateParameter("Yaw", p.Yaw)); + cmd.Parameters.Add(_Database.CreateParameter("Pitch", p.Pitch)); + cmd.Parameters.Add(_Database.CreateParameter("Distance", p.Distance)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + } + } + + public void SaveExtra(UUID regionID, string name, string value) + { + } + + public void RemoveExtra(UUID regionID, string name) + { + } + + public Dictionary GetExtra(UUID regionID) + { + return null; + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLUserAccountData.cs b/OpenSim/Data/PGSQL/PGSQLUserAccountData.cs new file mode 100644 index 0000000000..00f01cbb30 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLUserAccountData.cs @@ -0,0 +1,325 @@ +/* + * 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 OpenSimulator 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; +using System.Collections.Generic; +using System.Data; +using OpenMetaverse; +using OpenSim.Framework; +using System.Text; +using Npgsql; +using log4net; +using System.Reflection; + +namespace OpenSim.Data.PGSQL +{ + public class PGSQLUserAccountData : PGSQLGenericTableHandler,IUserAccountData + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + + public PGSQLUserAccountData(string connectionString, string realm) : + base(connectionString, realm, "UserAccount") + { + } + + /* + private string m_Realm; + private List m_ColumnNames = null; + private PGSQLManager m_database; + + public PGSQLUserAccountData(string connectionString, string realm) : + base(connectionString, realm, "UserAccount") + { + m_Realm = realm; + m_ConnectionString = connectionString; + m_database = new PGSQLManager(connectionString); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + { + conn.Open(); + Migration m = new Migration(conn, GetType().Assembly, "UserAccount"); + m.Update(); + } + } + */ + /* + public List Query(UUID principalID, UUID scopeID, string query) + { + return null; + } + */ + /* + public override UserAccountData[] Get(string[] fields, string[] keys) + { + UserAccountData[] retUA = base.Get(fields,keys); + + if (retUA.Length > 0) + { + Dictionary data = retUA[0].Data; + Dictionary data2 = new Dictionary(); + + foreach (KeyValuePair chave in data) + { + string s2 = chave.Key; + + data2[s2] = chave.Value; + + if (!m_FieldTypes.ContainsKey(chave.Key)) + { + string tipo = ""; + m_FieldTypes.TryGetValue(chave.Key, out tipo); + m_FieldTypes.Add(s2, tipo); + } + } + foreach (KeyValuePair chave in data2) + { + if (!retUA[0].Data.ContainsKey(chave.Key)) + retUA[0].Data.Add(chave.Key, chave.Value); + } + } + + return retUA; + } + */ + /* + public UserAccountData Get(UUID principalID, UUID scopeID) + { + UserAccountData ret = new UserAccountData(); + ret.Data = new Dictionary(); + + string sql = string.Format(@"select * from {0} where ""PrincipalID"" = :principalID", m_Realm); + if (scopeID != UUID.Zero) + sql += @" and ""ScopeID"" = :scopeID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + cmd.Parameters.Add(m_database.CreateParameter("principalID", principalID)); + cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); + + conn.Open(); + using (NpgsqlDataReader result = cmd.ExecuteReader()) + { + if (result.Read()) + { + ret.PrincipalID = principalID; + UUID scope; + UUID.TryParse(result["scopeid"].ToString(), out scope); + ret.ScopeID = scope; + + if (m_ColumnNames == null) + { + m_ColumnNames = new List(); + + DataTable schemaTable = result.GetSchemaTable(); + foreach (DataRow row in schemaTable.Rows) + m_ColumnNames.Add(row["ColumnName"].ToString()); + } + + foreach (string s in m_ColumnNames) + { + string s2 = s; + if (s2 == "uuid") + continue; + if (s2 == "scopeid") + continue; + + ret.Data[s] = result[s].ToString(); + } + return ret; + } + } + } + return null; + } + + + public override bool Store(UserAccountData data) + { + if (data.Data.ContainsKey("PrincipalID")) + data.Data.Remove("PrincipalID"); + if (data.Data.ContainsKey("ScopeID")) + data.Data.Remove("ScopeID"); + + string[] fields = new List(data.Data.Keys).ToArray(); + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + m_log.DebugFormat("[USER]: Try to update user {0} {1}", data.FirstName, data.LastName); + + StringBuilder updateBuilder = new StringBuilder(); + updateBuilder.AppendFormat("update {0} set ", m_Realm); + bool first = true; + foreach (string field in fields) + { + if (!first) + updateBuilder.Append(", "); + updateBuilder.AppendFormat("\"{0}\" = :{0}", field); + + first = false; + if (m_FieldTypes.ContainsKey(field)) + cmd.Parameters.Add(m_database.CreateParameter("" + field, data.Data[field], m_FieldTypes[field])); + else + cmd.Parameters.Add(m_database.CreateParameter("" + field, data.Data[field])); + } + + updateBuilder.Append(" where \"PrincipalID\" = :principalID"); + + if (data.ScopeID != UUID.Zero) + updateBuilder.Append(" and \"ScopeID\" = :scopeID"); + + cmd.CommandText = updateBuilder.ToString(); + cmd.Connection = conn; + cmd.Parameters.Add(m_database.CreateParameter("principalID", data.PrincipalID)); + cmd.Parameters.Add(m_database.CreateParameter("scopeID", data.ScopeID)); + + m_log.DebugFormat("[USER]: SQL update user {0} ", cmd.CommandText); + + conn.Open(); + + m_log.DebugFormat("[USER]: CON opened update user {0} ", cmd.CommandText); + + int conta = 0; + try + { + conta = cmd.ExecuteNonQuery(); + } + catch (Exception e){ + m_log.ErrorFormat("[USER]: ERROR opened update user {0} ", e.Message); + } + + + if (conta < 1) + { + m_log.DebugFormat("[USER]: Try to insert user {0} {1}", data.FirstName, data.LastName); + + StringBuilder insertBuilder = new StringBuilder(); + insertBuilder.AppendFormat(@"insert into {0} (""PrincipalID"", ""ScopeID"", ""FirstName"", ""LastName"", """, m_Realm); + insertBuilder.Append(String.Join(@""", """, fields)); + insertBuilder.Append(@""") values (:principalID, :scopeID, :FirstName, :LastName, :"); + insertBuilder.Append(String.Join(", :", fields)); + insertBuilder.Append(");"); + + cmd.Parameters.Add(m_database.CreateParameter("FirstName", data.FirstName)); + cmd.Parameters.Add(m_database.CreateParameter("LastName", data.LastName)); + + cmd.CommandText = insertBuilder.ToString(); + + if (cmd.ExecuteNonQuery() < 1) + { + return false; + } + } + else + m_log.DebugFormat("[USER]: User {0} {1} exists", data.FirstName, data.LastName); + } + return true; + } + + + public bool Store(UserAccountData data, UUID principalID, string token) + { + return false; + } + + + public bool SetDataItem(UUID principalID, string item, string value) + { + string sql = string.Format(@"update {0} set {1} = :{1} where ""UUID"" = :UUID", m_Realm, item); + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + if (m_FieldTypes.ContainsKey(item)) + cmd.Parameters.Add(m_database.CreateParameter("" + item, value, m_FieldTypes[item])); + else + cmd.Parameters.Add(m_database.CreateParameter("" + item, value)); + + cmd.Parameters.Add(m_database.CreateParameter("UUID", principalID)); + conn.Open(); + + if (cmd.ExecuteNonQuery() > 0) + return true; + } + return false; + } + */ + /* + public UserAccountData[] Get(string[] keys, string[] vals) + { + return null; + } + */ + + public UserAccountData[] GetUsers(UUID scopeID, string query) + { + string[] words = query.Split(new char[] { ' ' }); + + for (int i = 0; i < words.Length; i++) + { + if (words[i].Length < 3) + { + if (i != words.Length - 1) + Array.Copy(words, i + 1, words, i, words.Length - i - 1); + Array.Resize(ref words, words.Length - 1); + } + } + + if (words.Length == 0) + return new UserAccountData[0]; + + if (words.Length > 2) + return new UserAccountData[0]; + + string sql = ""; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + if (words.Length == 1) + { + sql = String.Format(@"select * from {0} where (""ScopeID""=:ScopeID or ""ScopeID""='00000000-0000-0000-0000-000000000000') and (""FirstName"" ilike :search or ""LastName"" ilike :search)", m_Realm); + cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); + cmd.Parameters.Add(m_database.CreateParameter("search", "%" + words[0] + "%")); + } + else + { + sql = String.Format(@"select * from {0} where (""ScopeID""=:ScopeID or ""ScopeID""='00000000-0000-0000-0000-000000000000') and (""FirstName"" ilike :searchFirst or ""LastName"" ilike :searchLast)", m_Realm); + cmd.Parameters.Add(m_database.CreateParameter("searchFirst", "%" + words[0] + "%")); + cmd.Parameters.Add(m_database.CreateParameter("searchLast", "%" + words[1] + "%")); + cmd.Parameters.Add(m_database.CreateParameter("ScopeID", scopeID.ToString())); + } + cmd.Connection = conn; + cmd.CommandText = sql; + conn.Open(); + return DoQuery(cmd); + } + } + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLUserProfilesData.cs b/OpenSim/Data/PGSQL/PGSQLUserProfilesData.cs new file mode 100644 index 0000000000..e3cbf7f513 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLUserProfilesData.cs @@ -0,0 +1,1075 @@ +/* + * 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 OpenSimulator 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.Data; +using System.Reflection; +using OpenSim.Data; +using OpenSim.Framework; +using OpenMetaverse; +using OpenMetaverse.StructuredData; +using log4net; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + public class UserProfilesData: IProfilesData + { + static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + #region Properites + string ConnectionString + { + get; set; + } + + protected object Lock + { + get; set; + } + + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + + #endregion Properties + + #region class Member Functions + public UserProfilesData(string connectionString) + { + ConnectionString = connectionString; + Init(); + } + + void Init() + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + + Migration m = new Migration(dbcon, Assembly, "UserProfiles"); + m.Update(); + } + } + #endregion Member Functions + + #region Classifieds Queries + /// + /// Gets the classified records. + /// + /// + /// Array of classified records + /// + /// + /// Creator identifier. + /// + public OSDArray GetClassifiedRecords(UUID creatorId) + { + OSDArray data = new OSDArray(); + + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + string query = @"SELECT ""classifieduuid"", ""name"" FROM classifieds WHERE ""creatoruuid"" = :Id"; + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("Id", creatorId); + using( NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default)) + { + if(reader.HasRows) + { + while (reader.Read()) + { + OSDMap n = new OSDMap(); + UUID Id = UUID.Zero; + + string Name = null; + try + { + UUID.TryParse(Convert.ToString( reader["classifieduuid"]), out Id); + Name = Convert.ToString(reader["name"]); + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": UserAccount exception {0}", e.Message); + } + n.Add("classifieduuid", OSD.FromUUID(Id)); + n.Add("name", OSD.FromString(Name)); + data.Add(n); + } + } + } + } + } + return data; + } + + public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result) + { + string query = @"INSERT INTO classifieds ( ""classifieduuid"",""creatoruuid"", ""creationdate"", ""expirationdate"", ""category"", + ""name"", ""description"", ""parceluuid"", ""parentestate"", ""snapshotuuid"", ""simname"", + ""posglobal"", ""parcelname"", ""classifiedflags"", ""priceforlisting"") + Select :ClassifiedId, :CreatorId, :CreatedDate, :ExpirationDate, :Category, + :Name, :Description, :ParcelId, :ParentEstate, :SnapshotId, :SimName + :GlobalPos, :ParcelName, :Flags, :ListingPrice + Where not exists( Select ""classifieduuid"" from classifieds where ""classifieduuid"" = :ClassifiedId ); + + update classifieds + set category =:Category, + expirationdate = :ExpirationDate, + name = :Name, + description = :Description, + parentestate = :ParentEstate, + posglobal = :GlobalPos, + parcelname = :ParcelName, + classifiedflags = :Flags, + priceforlisting = :ListingPrice, + snapshotuuid = :SnapshotId + where classifieduuid = :ClassifiedId ; + "; + + if(string.IsNullOrEmpty(ad.ParcelName)) + ad.ParcelName = "Unknown"; + if(ad.ParcelId == null) + ad.ParcelId = UUID.Zero; + if(string.IsNullOrEmpty(ad.Description)) + ad.Description = "No Description"; + + DateTime epoch = new DateTime(1970, 1, 1); + DateTime now = DateTime.Now; + TimeSpan epochnow = now - epoch; + TimeSpan duration; + DateTime expiration; + TimeSpan epochexp; + + if(ad.Flags == 2) + { + duration = new TimeSpan(7,0,0,0); + expiration = now.Add(duration); + epochexp = expiration - epoch; + } + else + { + duration = new TimeSpan(365,0,0,0); + expiration = now.Add(duration); + epochexp = expiration - epoch; + } + ad.CreationDate = (int)epochnow.TotalSeconds; + ad.ExpirationDate = (int)epochexp.TotalSeconds; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("ClassifiedId", ad.ClassifiedId.ToString()); + cmd.Parameters.AddWithValue("CreatorId", ad.CreatorId.ToString()); + cmd.Parameters.AddWithValue("CreatedDate", ad.CreationDate.ToString()); + cmd.Parameters.AddWithValue("ExpirationDate", ad.ExpirationDate.ToString()); + cmd.Parameters.AddWithValue("Category", ad.Category.ToString()); + cmd.Parameters.AddWithValue("Name", ad.Name.ToString()); + cmd.Parameters.AddWithValue("Description", ad.Description.ToString()); + cmd.Parameters.AddWithValue("ParcelId", ad.ParcelId.ToString()); + cmd.Parameters.AddWithValue("ParentEstate", ad.ParentEstate.ToString()); + cmd.Parameters.AddWithValue("SnapshotId", ad.SnapshotId.ToString ()); + cmd.Parameters.AddWithValue("SimName", ad.SimName.ToString()); + cmd.Parameters.AddWithValue("GlobalPos", ad.GlobalPos.ToString()); + cmd.Parameters.AddWithValue("ParcelName", ad.ParcelName.ToString()); + cmd.Parameters.AddWithValue("Flags", ad.Flags.ToString()); + cmd.Parameters.AddWithValue("ListingPrice", ad.Price.ToString ()); + + cmd.ExecuteNonQuery(); + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": ClassifiedesUpdate exception {0}", e.Message); + result = e.Message; + return false; + } + return true; + } + + + public bool DeleteClassifiedRecord(UUID recordId) + { + string query = string.Empty; + + query = @"DELETE FROM classifieds WHERE classifieduuid = :ClasifiedId ;"; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("ClassifiedId", recordId.ToString()); + + lock(Lock) + { + cmd.ExecuteNonQuery(); + } + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": DeleteClassifiedRecord exception {0}", e.Message); + return false; + } + return true; + } + + public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result) + { + string query = string.Empty; + + query += "SELECT * FROM classifieds WHERE "; + query += "classifieduuid = :AdId"; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("AdId", ad.ClassifiedId.ToString()); + + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if(reader.Read ()) + { + ad.CreatorId = GetUUID(reader["creatoruuid"]); + ad.ParcelId = GetUUID(reader["parceluuid"]); + ad.SnapshotId = GetUUID(reader["snapshotuuid"]); + ad.CreationDate = Convert.ToInt32(reader["creationdate"]); + ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]); + ad.ParentEstate = Convert.ToInt32(reader["parentestate"]); + ad.Flags = (byte)Convert.ToInt16(reader["classifiedflags"]); + ad.Category = Convert.ToInt32(reader["category"]); + ad.Price = Convert.ToInt16(reader["priceforlisting"]); + ad.Name = reader["name"].ToString(); + ad.Description = reader["description"].ToString(); + ad.SimName = reader["simname"].ToString(); + ad.GlobalPos = reader["posglobal"].ToString(); + ad.ParcelName = reader["parcelname"].ToString(); + + } + } + } + dbcon.Close(); + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": GetPickInfo exception {0}", e.Message); + } + return true; + } + + public static UUID GetUUID( object uuidValue ) { + + UUID ret = UUID.Zero; + + UUID.TryParse(uuidValue.ToString(), out ret); + + return ret; + } + + + #endregion Classifieds Queries + + #region Picks Queries + public OSDArray GetAvatarPicks(UUID avatarId) + { + string query = string.Empty; + + query += "SELECT \"pickuuid\",\"name\" FROM userpicks WHERE "; + query += "creatoruuid = :Id"; + OSDArray data = new OSDArray(); + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("Id", avatarId.ToString()); + + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if(reader.HasRows) + { + while (reader.Read()) + { + OSDMap record = new OSDMap(); + + record.Add("pickuuid",OSD.FromString((string)reader["pickuuid"])); + record.Add("name",OSD.FromString((string)reader["name"])); + data.Add(record); + } + } + } + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": GetAvatarPicks exception {0}", e.Message); + } + return data; + } + + public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId) + { + string query = string.Empty; + UserProfilePick pick = new UserProfilePick(); + + query += "SELECT * FROM userpicks WHERE "; + query += "creatoruuid = :CreatorId AND "; + query += "pickuuid = :PickId"; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("CreatorId", avatarId.ToString()); + cmd.Parameters.AddWithValue("PickId", pickId.ToString()); + + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if(reader.HasRows) + { + reader.Read(); + + string description = (string)reader["description"]; + + if (string.IsNullOrEmpty(description)) + description = "No description given."; + + UUID.TryParse((string)reader["pickuuid"], out pick.PickId); + UUID.TryParse((string)reader["creatoruuid"], out pick.CreatorId); + UUID.TryParse((string)reader["parceluuid"], out pick.ParcelId); + UUID.TryParse((string)reader["snapshotuuid"], out pick.SnapshotId); + pick.GlobalPos = (string)reader["posglobal"]; + bool.TryParse((string)reader["toppick"], out pick.TopPick); + bool.TryParse((string)reader["enabled"], out pick.Enabled); + pick.Name = (string)reader["name"]; + pick.Desc = description; + pick.User = (string)reader["user"]; + pick.OriginalName = (string)reader["originalname"]; + pick.SimName = (string)reader["simname"]; + pick.SortOrder = (int)reader["sortorder"]; + } + } + } + dbcon.Close(); + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": GetPickInfo exception {0}", e.Message); + } + return pick; + } + + public bool UpdatePicksRecord(UserProfilePick pick) + { + string query = string.Empty; + + query = @"INSERT INTO userpicks VALUES ( :PickId, :CreatorId, :TopPick, :ParcelId,:Name, :Desc, :SnapshotId,:User, + :Original, :SimName, :GlobalPos, :SortOrder, :Enabled) + where not exists ( select pickid from userpicks where pickid = :pickid); + + Update userpicks + set parceluuid = :ParcelId, + name = :Name, + description = :Desc, + snapshotuuid = :SnapshotId, + pickuuid = :PickId, + posglobal = :GlobalPos + where pickid = :PickId; + "; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("PickId", pick.PickId.ToString()); + cmd.Parameters.AddWithValue("CreatorId", pick.CreatorId.ToString()); + cmd.Parameters.AddWithValue("TopPick", pick.TopPick.ToString()); + cmd.Parameters.AddWithValue("ParcelId", pick.ParcelId.ToString()); + cmd.Parameters.AddWithValue("Name", pick.Name.ToString()); + cmd.Parameters.AddWithValue("Desc", pick.Desc.ToString()); + cmd.Parameters.AddWithValue("SnapshotId", pick.SnapshotId.ToString()); + cmd.Parameters.AddWithValue("User", pick.User.ToString()); + cmd.Parameters.AddWithValue("Original", pick.OriginalName.ToString()); + cmd.Parameters.AddWithValue("SimName",pick.SimName.ToString()); + cmd.Parameters.AddWithValue("GlobalPos", pick.GlobalPos); + cmd.Parameters.AddWithValue("SortOrder", pick.SortOrder.ToString ()); + cmd.Parameters.AddWithValue("Enabled", pick.Enabled.ToString()); + + cmd.ExecuteNonQuery(); + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": UpdateAvatarNotes exception {0}", e.Message); + return false; + } + return true; + } + + public bool DeletePicksRecord(UUID pickId) + { + string query = string.Empty; + + query += "DELETE FROM userpicks WHERE "; + query += "pickuuid = :PickId"; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("PickId", pickId.ToString()); + + cmd.ExecuteNonQuery(); + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": DeleteUserPickRecord exception {0}", e.Message); + return false; + } + return true; + } + #endregion Picks Queries + + #region Avatar Notes Queries + public bool GetAvatarNotes(ref UserProfileNotes notes) + { // WIP + string query = string.Empty; + + query += "SELECT \"notes\" FROM usernotes WHERE "; + query += "useruuid = :Id AND "; + query += "targetuuid = :TargetId"; + OSDArray data = new OSDArray(); + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("Id", notes.UserId.ToString()); + cmd.Parameters.AddWithValue("TargetId", notes.TargetId.ToString()); + + using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) + { + if(reader.HasRows) + { + reader.Read(); + notes.Notes = OSD.FromString((string)reader["notes"]); + } + } + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": GetAvatarNotes exception {0}", e.Message); + } + return true; + } + + public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result) + { + string query = string.Empty; + bool remove; + + if(string.IsNullOrEmpty(note.Notes)) + { + remove = true; + query += "DELETE FROM usernotes WHERE "; + query += "useruuid=:UserId AND "; + query += "targetuuid=:TargetId"; + } + else + { + remove = false; + query = @"INSERT INTO usernotes VALUES ( :UserId, :TargetId, :Notes ) + where not exists ( Select useruuid from usernotes where useruuid = :UserId and targetuuid = :TargetId ); + + update usernotes + set notes = :Notes + where useruuid = :UserId + and targetuuid = :TargetId; + "; + } + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + if(!remove) + cmd.Parameters.AddWithValue("Notes", note.Notes); + cmd.Parameters.AddWithValue("TargetId", note.TargetId.ToString ()); + cmd.Parameters.AddWithValue("UserId", note.UserId.ToString()); + + cmd.ExecuteNonQuery(); + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": UpdateAvatarNotes exception {0}", e.Message); + return false; + } + return true; + + } + #endregion Avatar Notes Queries + + #region Avatar Properties + public bool GetAvatarProperties(ref UserProfileProperties props, ref string result) + { + string query = string.Empty; + + query += "SELECT * FROM userprofile WHERE "; + query += "useruuid = :Id"; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("Id", props.UserId.ToString()); + + using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) + { + if(reader.HasRows) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": Getting data for {0}.", props.UserId); + reader.Read(); + props.WebUrl = (string)reader["profileURL"]; + UUID.TryParse((string)reader["profileImage"], out props.ImageId); + props.AboutText = (string)reader["profileAboutText"]; + UUID.TryParse((string)reader["profileFirstImage"], out props.FirstLifeImageId); + props.FirstLifeText = (string)reader["profileFirstText"]; + UUID.TryParse((string)reader["profilePartner"], out props.PartnerId); + props.WantToMask = (int)reader["profileWantToMask"]; + props.WantToText = (string)reader["profileWantToText"]; + props.SkillsMask = (int)reader["profileSkillsMask"]; + props.SkillsText = (string)reader["profileSkillsText"]; + props.Language = (string)reader["profileLanguages"]; + } + else + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": No data for {0}", props.UserId); + + props.WebUrl = string.Empty; + props.ImageId = UUID.Zero; + props.AboutText = string.Empty; + props.FirstLifeImageId = UUID.Zero; + props.FirstLifeText = string.Empty; + props.PartnerId = UUID.Zero; + props.WantToMask = 0; + props.WantToText = string.Empty; + props.SkillsMask = 0; + props.SkillsText = string.Empty; + props.Language = string.Empty; + props.PublishProfile = false; + props.PublishMature = false; + + query = "INSERT INTO userprofile ("; + query += "useruuid, "; + query += "profilePartner, "; + query += "profileAllowPublish, "; + query += "profileMaturePublish, "; + query += "profileURL, "; + query += "profileWantToMask, "; + query += "profileWantToText, "; + query += "profileSkillsMask, "; + query += "profileSkillsText, "; + query += "profileLanguages, "; + query += "profileImage, "; + query += "profileAboutText, "; + query += "profileFirstImage, "; + query += "profileFirstText) VALUES ("; + query += ":userId, "; + query += ":profilePartner, "; + query += ":profileAllowPublish, "; + query += ":profileMaturePublish, "; + query += ":profileURL, "; + query += ":profileWantToMask, "; + query += ":profileWantToText, "; + query += ":profileSkillsMask, "; + query += ":profileSkillsText, "; + query += ":profileLanguages, "; + query += ":profileImage, "; + query += ":profileAboutText, "; + query += ":profileFirstImage, "; + query += ":profileFirstText)"; + + dbcon.Close(); + dbcon.Open(); + + using (NpgsqlCommand put = new NpgsqlCommand(query, dbcon)) + { + put.Parameters.AddWithValue("userId", props.UserId.ToString()); + put.Parameters.AddWithValue("profilePartner", props.PartnerId.ToString()); + put.Parameters.AddWithValue("profileAllowPublish", props.PublishProfile); + put.Parameters.AddWithValue("profileMaturePublish", props.PublishMature); + put.Parameters.AddWithValue("profileURL", props.WebUrl); + put.Parameters.AddWithValue("profileWantToMask", props.WantToMask); + put.Parameters.AddWithValue("profileWantToText", props.WantToText); + put.Parameters.AddWithValue("profileSkillsMask", props.SkillsMask); + put.Parameters.AddWithValue("profileSkillsText", props.SkillsText); + put.Parameters.AddWithValue("profileLanguages", props.Language); + put.Parameters.AddWithValue("profileImage", props.ImageId.ToString()); + put.Parameters.AddWithValue("profileAboutText", props.AboutText); + put.Parameters.AddWithValue("profileFirstImage", props.FirstLifeImageId.ToString()); + put.Parameters.AddWithValue("profileFirstText", props.FirstLifeText); + + put.ExecuteNonQuery(); + } + } + } + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": Requst properties exception {0}", e.Message); + result = e.Message; + return false; + } + return true; + } + + public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result) + { + string query = string.Empty; + + query += "UPDATE userprofile SET "; + query += "profilePartner=:profilePartner, "; + query += "profileURL=:profileURL, "; + query += "profileImage=:image, "; + query += "profileAboutText=:abouttext,"; + query += "profileFirstImage=:firstlifeimage,"; + query += "profileFirstText=:firstlifetext "; + query += "WHERE useruuid=:uuid"; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("profileURL", props.WebUrl); + cmd.Parameters.AddWithValue("profilePartner", props.PartnerId.ToString()); + cmd.Parameters.AddWithValue("image", props.ImageId.ToString()); + cmd.Parameters.AddWithValue("abouttext", props.AboutText); + cmd.Parameters.AddWithValue("firstlifeimage", props.FirstLifeImageId.ToString()); + cmd.Parameters.AddWithValue("firstlifetext", props.FirstLifeText); + cmd.Parameters.AddWithValue("uuid", props.UserId.ToString()); + + cmd.ExecuteNonQuery(); + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": AgentPropertiesUpdate exception {0}", e.Message); + + return false; + } + return true; + } + #endregion Avatar Properties + + #region Avatar Interests + public bool UpdateAvatarInterests(UserProfileProperties up, ref string result) + { + string query = string.Empty; + + query += "UPDATE userprofile SET "; + query += "profileWantToMask=:WantMask, "; + query += "profileWantToText=:WantText,"; + query += "profileSkillsMask=:SkillsMask,"; + query += "profileSkillsText=:SkillsText, "; + query += "profileLanguages=:Languages "; + query += "WHERE useruuid=:uuid"; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("WantMask", up.WantToMask); + cmd.Parameters.AddWithValue("WantText", up.WantToText); + cmd.Parameters.AddWithValue("SkillsMask", up.SkillsMask); + cmd.Parameters.AddWithValue("SkillsText", up.SkillsText); + cmd.Parameters.AddWithValue("Languages", up.Language); + cmd.Parameters.AddWithValue("uuid", up.UserId.ToString()); + + cmd.ExecuteNonQuery(); + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": AgentInterestsUpdate exception {0}", e.Message); + result = e.Message; + return false; + } + return true; + } + #endregion Avatar Interests + + public OSDArray GetUserImageAssets(UUID avatarId) + { + OSDArray data = new OSDArray(); + string query = "SELECT \"snapshotuuid\" FROM {0} WHERE \"creatoruuid\" = :Id"; + + // Get classified image assets + + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + + using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format (query,"\"classifieds\""), dbcon)) + { + cmd.Parameters.AddWithValue("Id", avatarId.ToString()); + + using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) + { + if(reader.HasRows) + { + while (reader.Read()) + { + data.Add(new OSDString((string)reader["snapshotuuid"].ToString ())); + } + } + } + } + + dbcon.Close(); + dbcon.Open(); + + using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format (query,"\"userpicks\""), dbcon)) + { + cmd.Parameters.AddWithValue("Id", avatarId.ToString()); + + using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) + { + if(reader.HasRows) + { + while (reader.Read()) + { + data.Add(new OSDString((string)reader["snapshotuuid"].ToString ())); + } + } + } + } + + dbcon.Close(); + dbcon.Open(); + + query = "SELECT \"profileImage\", \"profileFirstImage\" FROM \"userprofile\" WHERE \"useruuid\" = :Id"; + + using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format (query,"\"userpicks\""), dbcon)) + { + cmd.Parameters.AddWithValue("Id", avatarId.ToString()); + + using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) + { + if(reader.HasRows) + { + while (reader.Read()) + { + data.Add(new OSDString((string)reader["profileImage"].ToString ())); + data.Add(new OSDString((string)reader["profileFirstImage"].ToString ())); + } + } + } + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": GetAvatarNotes exception {0}", e.Message); + } + return data; + } + + #region User Preferences + public OSDArray GetUserPreferences(UUID avatarId) + { + string query = string.Empty; + + query += "SELECT imviaemail,visible,email FROM "; + query += "usersettings WHERE "; + query += "useruuid = :Id"; + + OSDArray data = new OSDArray(); + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("Id", avatarId.ToString()); + + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + if(reader.HasRows) + { + reader.Read(); + OSDMap record = new OSDMap(); + + record.Add("imviaemail",OSD.FromString((string)reader["imviaemail"])); + record.Add("visible",OSD.FromString((string)reader["visible"])); + record.Add("email",OSD.FromString((string)reader["email"])); + data.Add(record); + } + else + { + using (NpgsqlCommand put = new NpgsqlCommand(query, dbcon)) + { + query = "INSERT INTO usersettings VALUES "; + query += "(:Id,'false','false', '')"; + + lock(Lock) + { + put.ExecuteNonQuery(); + } + } + } + } + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": Get preferences exception {0}", e.Message); + } + return data; + } + + public bool UpdateUserPreferences(bool emailIm, bool visible, UUID avatarId ) + { + string query = string.Empty; + + query += "UPDATE userpsettings SET "; + query += "imviaemail=:ImViaEmail, "; + query += "visible=:Visible,"; + query += "WHERE useruuid=:uuid"; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("ImViaEmail", emailIm.ToString().ToLower ()); + cmd.Parameters.AddWithValue("WantText", visible.ToString().ToLower ()); + cmd.Parameters.AddWithValue("uuid", avatarId.ToString()); + + lock(Lock) + { + cmd.ExecuteNonQuery(); + } + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": AgentInterestsUpdate exception {0}", e.Message); + return false; + } + return true; + } + #endregion User Preferences + + #region Integration + public bool GetUserAppData(ref UserAppData props, ref string result) + { + string query = string.Empty; + + query += "SELECT * FROM userdata WHERE "; + query += "\"UserId\" = :Id AND "; + query += "\"TagId\" = :TagId"; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("Id", props.UserId.ToString()); + cmd.Parameters.AddWithValue (":TagId", props.TagId.ToString()); + + using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) + { + if(reader.HasRows) + { + reader.Read(); + props.DataKey = (string)reader["DataKey"]; + props.DataVal = (string)reader["DataVal"]; + } + else + { + query += "INSERT INTO userdata VALUES ( "; + query += ":UserId,"; + query += ":TagId,"; + query += ":DataKey,"; + query += ":DataVal) "; + + using (NpgsqlCommand put = new NpgsqlCommand(query, dbcon)) + { + put.Parameters.AddWithValue("Id", props.UserId.ToString()); + put.Parameters.AddWithValue("TagId", props.TagId.ToString()); + put.Parameters.AddWithValue("DataKey", props.DataKey.ToString()); + put.Parameters.AddWithValue("DataVal", props.DataVal.ToString()); + + lock(Lock) + { + put.ExecuteNonQuery(); + } + } + } + } + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": Requst application data exception {0}", e.Message); + result = e.Message; + return false; + } + return true; + } + + public bool SetUserAppData(UserAppData props, ref string result) + { + string query = string.Empty; + + query += "UPDATE userdata SET "; + query += "\"TagId\" = :TagId, "; + query += "\"DataKey\" = :DataKey, "; + query += "\"DataVal\" = :DataVal WHERE "; + query += "\"UserId\" = :UserId AND "; + query += "\"TagId\" = :TagId"; + + try + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) + { + cmd.Parameters.AddWithValue("UserId", props.UserId.ToString()); + cmd.Parameters.AddWithValue("TagId", props.TagId.ToString ()); + cmd.Parameters.AddWithValue("DataKey", props.DataKey.ToString ()); + cmd.Parameters.AddWithValue("DataVal", props.DataKey.ToString ()); + + lock(Lock) + { + cmd.ExecuteNonQuery(); + } + } + } + } + catch (Exception e) + { + m_log.DebugFormat("[PROFILES_DATA]" + + ": SetUserData exception {0}", e.Message); + return false; + } + return true; + } + #endregion Integration + } +} + diff --git a/OpenSim/Data/PGSQL/PGSQLXAssetData.cs b/OpenSim/Data/PGSQL/PGSQLXAssetData.cs new file mode 100644 index 0000000000..e959619ed0 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLXAssetData.cs @@ -0,0 +1,535 @@ +/* + * 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 OpenSimulator 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.IO; +using System.IO.Compression; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Data; +using Npgsql; + +namespace OpenSim.Data.PGSQL +{ + public class PGSQLXAssetData : IXAssetDataPlugin + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + + /// + /// Number of days that must pass before we update the access time on an asset when it has been fetched. + /// + private const int DaysBetweenAccessTimeUpdates = 30; + + private bool m_enableCompression = false; + private string m_connectionString; + private object m_dbLock = new object(); + + /// + /// We can reuse this for all hashing since all methods are single-threaded through m_dbBLock + /// + private HashAlgorithm hasher = new SHA256CryptoServiceProvider(); + + #region IPlugin Members + + public string Version { get { return "1.0.0.0"; } } + + /// + /// Initialises Asset interface + /// + /// + /// Loads and initialises the PGSQL storage plugin. + /// Warns and uses the obsolete pgsql_connection.ini if connect string is empty. + /// Check for migration + /// + /// + /// + /// connect string + public void Initialise(string connect) + { + m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); + m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); + m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); + m_log.ErrorFormat("[PGSQL XASSETDATA]: THIS PLUGIN IS STRICTLY EXPERIMENTAL."); + m_log.ErrorFormat("[PGSQL XASSETDATA]: DO NOT USE FOR ANY DATA THAT YOU DO NOT MIND LOSING."); + m_log.ErrorFormat("[PGSQL XASSETDATA]: DATABASE TABLES CAN CHANGE AT ANY TIME, CAUSING EXISTING DATA TO BE LOST."); + m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); + m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); + m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); + + m_connectionString = connect; + + using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) + { + dbcon.Open(); + Migration m = new Migration(dbcon, Assembly, "XAssetStore"); + m.Update(); + } + } + + public void Initialise() + { + throw new NotImplementedException(); + } + + public void Dispose() { } + + /// + /// The name of this DB provider + /// + public string Name + { + get { return "PGSQL XAsset storage engine"; } + } + + #endregion + + #region IAssetDataPlugin Members + + /// + /// Fetch Asset from database + /// + /// Asset UUID to fetch + /// Return the asset + /// On failure : throw an exception and attempt to reconnect to database + public AssetBase GetAsset(UUID assetID) + { +// m_log.DebugFormat("[PGSQL XASSET DATA]: Looking for asset {0}", assetID); + + AssetBase asset = null; + lock (m_dbLock) + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) + { + dbcon.Open(); + + using (NpgsqlCommand cmd = new NpgsqlCommand( + @"SELECT ""Name"", ""Description"", ""AccessTime"", ""AssetType"", ""Local"", ""Temporary"", ""AssetFlags"", ""CreatorID"", ""Data"" + FROM XAssetsMeta + JOIN XAssetsData ON XAssetsMeta.Hash = XAssetsData.Hash WHERE ""ID""=:ID", + dbcon)) + { + cmd.Parameters.AddWithValue("ID", assetID.ToString()); + + try + { + using (NpgsqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) + { + if (dbReader.Read()) + { + asset = new AssetBase(assetID, (string)dbReader["Name"], (sbyte)dbReader["AssetType"], dbReader["CreatorID"].ToString()); + asset.Data = (byte[])dbReader["Data"]; + asset.Description = (string)dbReader["Description"]; + + string local = dbReader["Local"].ToString(); + if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase)) + asset.Local = true; + else + asset.Local = false; + + asset.Temporary = Convert.ToBoolean(dbReader["Temporary"]); + asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]); + + if (m_enableCompression) + { + using (GZipStream decompressionStream = new GZipStream(new MemoryStream(asset.Data), CompressionMode.Decompress)) + { + MemoryStream outputStream = new MemoryStream(); + WebUtil.CopyStream(decompressionStream, outputStream, int.MaxValue); + // int compressedLength = asset.Data.Length; + asset.Data = outputStream.ToArray(); + + // m_log.DebugFormat( + // "[XASSET DB]: Decompressed {0} {1} to {2} bytes from {3}", + // asset.ID, asset.Name, asset.Data.Length, compressedLength); + } + } + + UpdateAccessTime(asset.Metadata, (int)dbReader["AccessTime"]); + } + } + } + catch (Exception e) + { + m_log.Error(string.Format("[PGSQL XASSET DATA]: Failure fetching asset {0}", assetID), e); + } + } + } + } + + return asset; + } + + /// + /// Create an asset in database, or update it if existing. + /// + /// Asset UUID to create + /// On failure : Throw an exception and attempt to reconnect to database + public void StoreAsset(AssetBase asset) + { +// m_log.DebugFormat("[XASSETS DB]: Storing asset {0} {1}", asset.Name, asset.ID); + + lock (m_dbLock) + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) + { + dbcon.Open(); + + using (NpgsqlTransaction transaction = dbcon.BeginTransaction()) + { + string assetName = asset.Name; + if (asset.Name.Length > 64) + { + assetName = asset.Name.Substring(0, 64); + m_log.WarnFormat( + "[XASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add", + asset.Name, asset.ID, asset.Name.Length, assetName.Length); + } + + string assetDescription = asset.Description; + if (asset.Description.Length > 64) + { + assetDescription = asset.Description.Substring(0, 64); + m_log.WarnFormat( + "[XASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add", + asset.Description, asset.ID, asset.Description.Length, assetDescription.Length); + } + + if (m_enableCompression) + { + MemoryStream outputStream = new MemoryStream(); + + using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress, false)) + { + // Console.WriteLine(WebUtil.CopyTo(new MemoryStream(asset.Data), compressionStream, int.MaxValue)); + // We have to close the compression stream in order to make sure it writes everything out to the underlying memory output stream. + compressionStream.Close(); + byte[] compressedData = outputStream.ToArray(); + asset.Data = compressedData; + } + } + + byte[] hash = hasher.ComputeHash(asset.Data); + +// m_log.DebugFormat( +// "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}", +// asset.ID, asset.Name, hash, compressedData.Length); + + try + { + using (NpgsqlCommand cmd = + new NpgsqlCommand( + @"insert INTO XAssetsMeta(""ID"", ""Hash"", ""Name"", ""Description"", ""AssetType"", ""Local"", ""Temporary"", ""CreateTime"", ""AccessTime"", ""AssetFlags"", ""CreatorID"") + Select :ID, :Hash, :Name, :Description, :AssetType, :Local, :Temporary, :CreateTime, :AccessTime, :AssetFlags, :CreatorID + where not exists( Select ""ID"" from XAssetsMeta where ""ID"" = :ID ; + + update XAssetsMeta + set ""ID"" = :ID, ""Hash"" = :Hash, ""Name"" = :Name, ""Description"" = :Description, + ""AssetType"" = :AssetType, ""Local"" = :Local, ""Temporary"" = :Temporary, ""CreateTime"" = :CreateTime, + ""AccessTime"" = :AccessTime, ""AssetFlags"" = :AssetFlags, ""CreatorID"" = :CreatorID + where ""ID"" = :ID; + ", + dbcon)) + { + // create unix epoch time + int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow); + cmd.Parameters.AddWithValue("ID", asset.ID); + cmd.Parameters.AddWithValue("Hash", hash); + cmd.Parameters.AddWithValue("Name", assetName); + cmd.Parameters.AddWithValue("Description", assetDescription); + cmd.Parameters.AddWithValue("AssetType", asset.Type); + cmd.Parameters.AddWithValue("Local", asset.Local); + cmd.Parameters.AddWithValue("Temporary", asset.Temporary); + cmd.Parameters.AddWithValue("CreateTime", now); + cmd.Parameters.AddWithValue("AccessTime", now); + cmd.Parameters.AddWithValue("CreatorID", asset.Metadata.CreatorID); + cmd.Parameters.AddWithValue("AssetFlags", (int)asset.Flags); + cmd.ExecuteNonQuery(); + } + } + catch (Exception e) + { + m_log.ErrorFormat("[ASSET DB]: PGSQL failure creating asset metadata {0} with name \"{1}\". Error: {2}", + asset.FullID, asset.Name, e.Message); + + transaction.Rollback(); + + return; + } + + if (!ExistsData(dbcon, transaction, hash)) + { + try + { + using (NpgsqlCommand cmd = + new NpgsqlCommand( + @"INSERT INTO XAssetsData(""Hash"", ""Data"") VALUES(:Hash, :Data)", + dbcon)) + { + cmd.Parameters.AddWithValue("Hash", hash); + cmd.Parameters.AddWithValue("Data", asset.Data); + cmd.ExecuteNonQuery(); + } + } + catch (Exception e) + { + m_log.ErrorFormat("[XASSET DB]: PGSQL failure creating asset data {0} with name \"{1}\". Error: {2}", + asset.FullID, asset.Name, e.Message); + + transaction.Rollback(); + + return; + } + } + + transaction.Commit(); + } + } + } + } + + /// + /// Updates the access time of the asset if it was accessed above a given threshhold amount of time. + /// + /// + /// This gives us some insight into assets which haven't ben accessed for a long period. This is only done + /// over the threshold time to avoid excessive database writes as assets are fetched. + /// + /// + /// + private void UpdateAccessTime(AssetMetadata assetMetadata, int accessTime) + { + DateTime now = DateTime.UtcNow; + + if ((now - Utils.UnixTimeToDateTime(accessTime)).TotalDays < DaysBetweenAccessTimeUpdates) + return; + + lock (m_dbLock) + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) + { + dbcon.Open(); + NpgsqlCommand cmd = + new NpgsqlCommand(@"update XAssetsMeta set ""AccessTime""=:AccessTime where ID=:ID", dbcon); + + try + { + using (cmd) + { + // create unix epoch time + cmd.Parameters.AddWithValue("ID", assetMetadata.ID); + cmd.Parameters.AddWithValue("AccessTime", (int)Utils.DateTimeToUnixTime(now)); + cmd.ExecuteNonQuery(); + } + } + catch (Exception e) + { + m_log.ErrorFormat( + "[XASSET PGSQL DB]: Failure updating access_time for asset {0} with name {1} : {2}", + assetMetadata.ID, assetMetadata.Name, e.Message); + } + } + } + } + + /// + /// We assume we already have the m_dbLock. + /// + /// TODO: need to actually use the transaction. + /// + /// + /// + /// + private bool ExistsData(NpgsqlConnection dbcon, NpgsqlTransaction transaction, byte[] hash) + { +// m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid); + + bool exists = false; + + using (NpgsqlCommand cmd = new NpgsqlCommand(@"SELECT ""Hash"" FROM XAssetsData WHERE ""Hash""=:Hash", dbcon)) + { + cmd.Parameters.AddWithValue("Hash", hash); + + try + { + using (NpgsqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) + { + if (dbReader.Read()) + { +// m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid); + exists = true; + } + } + } + catch (Exception e) + { + m_log.ErrorFormat( + "[XASSETS DB]: PGSql failure in ExistsData fetching hash {0}. Exception {1}{2}", + hash, e.Message, e.StackTrace); + } + } + + return exists; + } + + /// + /// Check if the asset exists in the database + /// + /// The asset UUID + /// true if it exists, false otherwise. + public bool ExistsAsset(UUID uuid) + { +// m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid); + + bool assetExists = false; + + lock (m_dbLock) + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) + { + dbcon.Open(); + using (NpgsqlCommand cmd = new NpgsqlCommand(@"SELECT ""ID"" FROM XAssetsMeta WHERE ""ID""=:ID", dbcon)) + { + cmd.Parameters.AddWithValue("ID", uuid.ToString()); + + try + { + using (NpgsqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) + { + if (dbReader.Read()) + { +// m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid); + assetExists = true; + } + } + } + catch (Exception e) + { + m_log.Error(string.Format("[XASSETS DB]: PGSql failure fetching asset {0}", uuid), e); + } + } + } + } + + return assetExists; + } + + + /// + /// Returns a list of AssetMetadata objects. The list is a subset of + /// the entire data set offset by containing + /// elements. + /// + /// The number of results to discard from the total data set. + /// The number of rows the returned list should contain. + /// A list of AssetMetadata objects. + public List FetchAssetMetadataSet(int start, int count) + { + List retList = new List(count); + + lock (m_dbLock) + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) + { + dbcon.Open(); + NpgsqlCommand cmd = new NpgsqlCommand( @"SELECT ""Name"", ""Description"", ""AccessTime"", ""AssetType"", ""Temporary"", ""ID"", ""AssetFlags"", ""CreatorID"" + FROM XAssetsMeta + LIMIT :start, :count", dbcon); + cmd.Parameters.AddWithValue("start", start); + cmd.Parameters.AddWithValue("count", count); + + try + { + using (NpgsqlDataReader dbReader = cmd.ExecuteReader()) + { + while (dbReader.Read()) + { + AssetMetadata metadata = new AssetMetadata(); + metadata.Name = (string)dbReader["Name"]; + metadata.Description = (string)dbReader["Description"]; + metadata.Type = (sbyte)dbReader["AssetType"]; + metadata.Temporary = Convert.ToBoolean(dbReader["Temporary"]); // Not sure if this is correct. + metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]); + metadata.FullID = DBGuid.FromDB(dbReader["ID"]); + metadata.CreatorID = dbReader["CreatorID"].ToString(); + + // We'll ignore this for now - it appears unused! +// metadata.SHA1 = dbReader["hash"]); + + UpdateAccessTime(metadata, (int)dbReader["AccessTime"]); + + retList.Add(metadata); + } + } + } + catch (Exception e) + { + m_log.Error("[XASSETS DB]: PGSql failure fetching asset set" + Environment.NewLine + e.ToString()); + } + } + } + + return retList; + } + + public bool Delete(string id) + { +// m_log.DebugFormat("[XASSETS DB]: Deleting asset {0}", id); + + lock (m_dbLock) + { + using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) + { + dbcon.Open(); + + using (NpgsqlCommand cmd = new NpgsqlCommand(@"delete from XAssetsMeta where ""ID""=:ID", dbcon)) + { + cmd.Parameters.AddWithValue("ID", id); + cmd.ExecuteNonQuery(); + } + + // TODO: How do we deal with data from deleted assets? Probably not easily reapable unless we + // keep a reference count (?) + } + } + + return true; + } + + #endregion + } +} diff --git a/OpenSim/Data/PGSQL/PGSQLXInventoryData.cs b/OpenSim/Data/PGSQL/PGSQLXInventoryData.cs new file mode 100644 index 0000000000..a22b882c01 --- /dev/null +++ b/OpenSim/Data/PGSQL/PGSQLXInventoryData.cs @@ -0,0 +1,330 @@ +/* + * 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 OpenSimulator 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; +using System.Collections.Generic; +using System.Data; +using OpenMetaverse; +using OpenSim.Framework; +using System.Reflection; +using System.Text; +using log4net; +using Npgsql; +using NpgsqlTypes; + +namespace OpenSim.Data.PGSQL +{ + public class PGSQLXInventoryData : IXInventoryData + { +// private static readonly ILog m_log = LogManager.GetLogger( +// MethodBase.GetCurrentMethod().DeclaringType); + + private PGSQLFolderHandler m_Folders; + private PGSQLItemHandler m_Items; + + public PGSQLXInventoryData(string conn, string realm) + { + m_Folders = new PGSQLFolderHandler( + conn, "inventoryfolders", "InventoryStore"); + m_Items = new PGSQLItemHandler( + conn, "inventoryitems", String.Empty); + } + + public static UUID str2UUID(string strUUID) + { + UUID newUUID = UUID.Zero; + + UUID.TryParse(strUUID, out newUUID); + + return newUUID; + } + + public XInventoryFolder[] GetFolders(string[] fields, string[] vals) + { + return m_Folders.Get(fields, vals); + } + + public XInventoryItem[] GetItems(string[] fields, string[] vals) + { + return m_Items.Get(fields, vals); + } + + public bool StoreFolder(XInventoryFolder folder) + { + if (folder.folderName.Length > 64) + folder.folderName = folder.folderName.Substring(0, 64); + return m_Folders.Store(folder); + } + + public bool StoreItem(XInventoryItem item) + { + if (item.inventoryName.Length > 64) + item.inventoryName = item.inventoryName.Substring(0, 64); + if (item.inventoryDescription.Length > 128) + item.inventoryDescription = item.inventoryDescription.Substring(0, 128); + + return m_Items.Store(item); + } + + public bool DeleteFolders(string field, string val) + { + return m_Folders.Delete(field, val); + } + + public bool DeleteFolders(string[] fields, string[] vals) + { + return m_Folders.Delete(fields, vals); + } + + public bool DeleteItems(string field, string val) + { + return m_Items.Delete(field, val); + } + + public bool DeleteItems(string[] fields, string[] vals) + { + return m_Items.Delete(fields, vals); + } + + public bool MoveItem(string id, string newParent) + { + return m_Items.MoveItem(id, newParent); + } + + public bool MoveFolder(string id, string newParent) + { + return m_Folders.MoveFolder(id, newParent); + } + + public XInventoryItem[] GetActiveGestures(UUID principalID) + { + return m_Items.GetActiveGestures(principalID.ToString()); + } + + public int GetAssetPermissions(UUID principalID, UUID assetID) + { + return m_Items.GetAssetPermissions(principalID, assetID); + } + } + + public class PGSQLItemHandler : PGSQLInventoryHandler + { + public PGSQLItemHandler(string c, string t, string m) : + base(c, t, m) + { + } + + public bool MoveItem(string id, string newParent) + { + XInventoryItem[] retrievedItems = Get(new string[] { "inventoryID" }, new string[] { id }); + if (retrievedItems.Length == 0) + return false; + + UUID oldParent = retrievedItems[0].parentFolderID; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + { + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + cmd.CommandText = String.Format(@"update {0} set ""parentFolderID"" = :ParentFolderID where ""inventoryID"" = :InventoryID", m_Realm); + cmd.Parameters.Add(m_database.CreateParameter("ParentFolderID", newParent)); + cmd.Parameters.Add(m_database.CreateParameter("InventoryID", id )); + cmd.Connection = conn; + conn.Open(); + + if (cmd.ExecuteNonQuery() == 0) + return false; + } + } + + IncrementFolderVersion(oldParent); + IncrementFolderVersion(newParent); + + return true; + } + + public XInventoryItem[] GetActiveGestures(string principalID) + { + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + { + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + cmd.CommandText = String.Format(@"select * from inventoryitems where ""avatarID"" = :uuid and ""assetType"" = :type and ""flags"" = 1", m_Realm); + + UUID princID = UUID.Zero; + UUID.TryParse(principalID, out princID); + + cmd.Parameters.Add(m_database.CreateParameter("uuid", principalID)); + cmd.Parameters.Add(m_database.CreateParameter("type", (int)AssetType.Gesture)); + cmd.Connection = conn; + conn.Open(); + return DoQuery(cmd); + } + } + } + + public int GetAssetPermissions(UUID principalID, UUID assetID) + { + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + { + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + cmd.CommandText = String.Format(@"select bit_or(""inventoryCurrentPermissions"") as ""inventoryCurrentPermissions"" + from inventoryitems + where ""avatarID"" = :PrincipalID + and ""assetID"" = :AssetID + group by ""assetID"" ", m_Realm); + + cmd.Parameters.Add(m_database.CreateParameter("PrincipalID", principalID)); + cmd.Parameters.Add(m_database.CreateParameter("AssetID", assetID)); + cmd.Connection = conn; + conn.Open(); + using (NpgsqlDataReader reader = cmd.ExecuteReader()) + { + + int perms = 0; + + if (reader.Read()) + { + perms = Convert.ToInt32(reader["inventoryCurrentPermissions"]); + } + + return perms; + } + + } + } + } + + public override bool Store(XInventoryItem item) + { + if (!base.Store(item)) + return false; + + IncrementFolderVersion(item.parentFolderID); + + return true; + } + } + + public class PGSQLFolderHandler : PGSQLInventoryHandler + { + public PGSQLFolderHandler(string c, string t, string m) : + base(c, t, m) + { + } + + public bool MoveFolder(string id, string newParentFolderID) + { + XInventoryFolder[] folders = Get(new string[] { "folderID" }, new string[] { id }); + + if (folders.Length == 0) + return false; + + UUID oldParentFolderUUID = folders[0].parentFolderID; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + { + using (NpgsqlCommand cmd = new NpgsqlCommand()) + { + UUID foldID = UUID.Zero; + UUID.TryParse(id, out foldID); + + UUID newPar = UUID.Zero; + UUID.TryParse(newParentFolderID, out newPar); + + cmd.CommandText = String.Format(@"update {0} set ""parentFolderID"" = :ParentFolderID where ""folderID"" = :folderID", m_Realm); + cmd.Parameters.Add(m_database.CreateParameter("ParentFolderID", newPar)); + cmd.Parameters.Add(m_database.CreateParameter("folderID", foldID)); + cmd.Connection = conn; + conn.Open(); + + if (cmd.ExecuteNonQuery() == 0) + return false; + } + } + + IncrementFolderVersion(oldParentFolderUUID); + IncrementFolderVersion(newParentFolderID); + + return true; + } + + public override bool Store(XInventoryFolder folder) + { + if (!base.Store(folder)) + return false; + + IncrementFolderVersion(folder.parentFolderID); + + return true; + } + } + + public class PGSQLInventoryHandler : PGSQLGenericTableHandler where T: class, new() + { + public PGSQLInventoryHandler(string c, string t, string m) : base(c, t, m) {} + + protected bool IncrementFolderVersion(UUID folderID) + { + return IncrementFolderVersion(folderID.ToString()); + } + + protected bool IncrementFolderVersion(string folderID) + { +// m_log.DebugFormat("[PGSQL ITEM HANDLER]: Incrementing version on folder {0}", folderID); +// Util.PrintCallStack(); + + string sql = @"update inventoryfolders set version=version+1 where ""folderID"" = :folderID"; + + using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) + { + using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) + { + UUID foldID = UUID.Zero; + UUID.TryParse(folderID, out foldID); + + conn.Open(); + + cmd.Parameters.Add( m_database.CreateParameter("folderID", foldID) ); + + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception) + { + return false; + } + } + } + + return true; + } + } +} diff --git a/OpenSim/Data/PGSQL/Properties/AssemblyInfo.cs b/OpenSim/Data/PGSQL/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..27d06790ea --- /dev/null +++ b/OpenSim/Data/PGSQL/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 OpenSimulator 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.Data.PGSQL")] +[assembly : AssemblyDescription("")] +[assembly : AssemblyConfiguration("")] +[assembly : AssemblyCompany("http://opensimulator.org")] +[assembly : AssemblyProduct("OpenSim.Data.PGSQL")] +[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")] +[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("0.7.6.*")] + diff --git a/OpenSim/Data/PGSQL/Resources/AssetStore.migrations b/OpenSim/Data/PGSQL/Resources/AssetStore.migrations new file mode 100644 index 0000000000..b6db58595b --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/AssetStore.migrations @@ -0,0 +1,94 @@ +:VERSION 1 + +CREATE TABLE assets ( + "id" varchar(36) NOT NULL PRIMARY KEY, + "name" varchar(64) NOT NULL, + "description" varchar(64) NOT NULL, + "assetType" smallint NOT NULL, + "local" smallint NOT NULL, + "temporary" smallint NOT NULL, + "data" bytea NOT NULL +) ; + +:VERSION 2 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_assets + ( + "id" varchar(36) NOT NULL, + "name" varchar(64) NOT NULL, + "description" varchar(64) NOT NULL, + "assetType" smallint NOT NULL, + "local" boolean NOT NULL, + "temporary" boolean NOT NULL, + "data" bytea NOT NULL + ) ; + +INSERT INTO Tmp_assets ("id", "name", "description", "assetType", "local", "temporary", "data") + SELECT "id", "name", "description", "assetType", case when "local" = 1 then true else false end, case when "temporary" = 1 then true else false end, "data" + FROM assets ; + +DROP TABLE assets; + +Alter table Tmp_assets + rename to assets; + +ALTER TABLE assets ADD PRIMARY KEY ("id"); + +COMMIT; + + +:VERSION 3 + +BEGIN TRANSACTION; + +ALTER TABLE assets add "create_time" integer default 0; +ALTER TABLE assets add "access_time" integer default 0; + +COMMIT; + + +:VERSION 4 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_assets + ( + "id" uuid NOT NULL, + "name" varchar(64) NOT NULL, + "description" varchar(64) NOT NULL, + "assetType" smallint NOT NULL, + "local" boolean NOT NULL, + "temporary" boolean NOT NULL, + "data" bytea NOT NULL, + "create_time" int NULL, + "access_time" int NULL + ) ; + + +INSERT INTO Tmp_assets ("id", "name", "description", "assetType", "local", "temporary", "data", "create_time", "access_time") + SELECT cast("id" as uuid), "name", "description", "assetType", "local", "temporary", "data", "create_time", "access_time" + FROM assets ; + +DROP TABLE assets; + +Alter table Tmp_assets + rename to assets; + + ALTER TABLE assets ADD PRIMARY KEY ("id"); + +COMMIT; + + +:VERSION 5 + +DELETE FROM assets WHERE "id" = 'dc4b9f0b-d008-45c6-96a4-01dd947ac621'; + +:VERSION 6 + +ALTER TABLE assets ADD "asset_flags" INTEGER NOT NULL DEFAULT 0; + +:VERSION 7 + +alter table assets add "creatorid" varchar(36) not null default ''; diff --git a/OpenSim/Data/PGSQL/Resources/AuthStore.migrations b/OpenSim/Data/PGSQL/Resources/AuthStore.migrations new file mode 100644 index 0000000000..a1f5b61ef6 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/AuthStore.migrations @@ -0,0 +1,32 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE auth ( + uuid uuid NOT NULL default '00000000-0000-0000-0000-000000000000', + "passwordHash" varchar(32) NOT NULL, + "passwordSalt" varchar(32) NOT NULL, + "webLoginKey" varchar(255) NOT NULL, + "accountType" VARCHAR(32) NOT NULL DEFAULT 'UserAccount' +) ; + +CREATE TABLE tokens ( + uuid uuid NOT NULL default '00000000-0000-0000-0000-000000000000', + token varchar(255) NOT NULL, + validity TIMESTAMP NOT NULL ) + ; + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + + INSERT INTO auth (uuid, "passwordHash", "passwordSalt", "webLoginKey", "accountType") + SELECT uuid AS UUID, passwordHash AS passwordHash, passwordSalt AS passwordSalt, webLoginKey AS webLoginKey, 'UserAccount' as accountType + FROM users + where exists ( Select * from information_schema.tables where table_name = 'users' ) + ; + +COMMIT; + diff --git a/OpenSim/Data/PGSQL/Resources/Avatar.migrations b/OpenSim/Data/PGSQL/Resources/Avatar.migrations new file mode 100644 index 0000000000..160086d77c --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/Avatar.migrations @@ -0,0 +1,59 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE Avatars ( +"PrincipalID" uuid NOT NULL PRIMARY KEY, +"Name" varchar(32) NOT NULL, +"Value" varchar(255) NOT NULL DEFAULT '' +); + + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_Avatars + ( + "PrincipalID" uuid NOT NULL, + "Name" varchar(32) NOT NULL, + "Value" text NOT NULL DEFAULT '' + ) ; + + INSERT INTO Tmp_Avatars ("PrincipalID", "Name", "Value") + SELECT "PrincipalID", cast("Name" as text), "Value" + FROM Avatars ; + +DROP TABLE Avatars; + +Alter table Tmp_Avatars + rename to Avatars; + +COMMIT; + +:VERSION 3 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_Avatars + ( + "PrincipalID" uuid NOT NULL, + "Name" varchar(32) NOT NULL, + "Value" text NOT NULL DEFAULT '' +); + +ALTER TABLE Tmp_Avatars ADD PRIMARY KEY ("PrincipalID", "Name"); + + +INSERT INTO Tmp_Avatars ("PrincipalID", "Name", "Value") + SELECT "PrincipalID", "Name", cast("Value" as text) FROM Avatars ; + +DROP TABLE Avatars; + +Alter table Tmp_Avatars + rename to Avatars; + +COMMIT; + diff --git a/OpenSim/Data/PGSQL/Resources/EstateStore.migrations b/OpenSim/Data/PGSQL/Resources/EstateStore.migrations new file mode 100644 index 0000000000..59270f8b01 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/EstateStore.migrations @@ -0,0 +1,307 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE estate_managers( + "EstateID" int NOT NULL Primary Key, + uuid varchar(36) NOT NULL + ); + +CREATE TABLE estate_groups( + "EstateID" int NOT NULL, + uuid varchar(36) NOT NULL + ); + + +CREATE TABLE estate_users( + "EstateID" int NOT NULL, + uuid varchar(36) NOT NULL + ); + + +CREATE TABLE estateban( + "EstateID" int NOT NULL, + "bannedUUID" varchar(36) NOT NULL, + "bannedIp" varchar(16) NOT NULL, + "bannedIpHostMask" varchar(16) NOT NULL, + "bannedNameMask" varchar(64) NULL DEFAULT NULL + ); + +Create Sequence estate_settings_id increment by 100 start with 100; + +CREATE TABLE estate_settings( + "EstateID" integer DEFAULT nextval('estate_settings_id') NOT NULL, + "EstateName" varchar(64) NULL DEFAULT (NULL), + "AbuseEmailToEstateOwner" boolean NOT NULL, + "DenyAnonymous" boolean NOT NULL, + "ResetHomeOnTeleport" boolean NOT NULL, + "FixedSun" boolean NOT NULL, + "DenyTransacted" boolean NOT NULL, + "BlockDwell" boolean NOT NULL, + "DenyIdentified" boolean NOT NULL, + "AllowVoice" boolean NOT NULL, + "UseGlobalTime" boolean NOT NULL, + "PricePerMeter" int NOT NULL, + "TaxFree" boolean NOT NULL, + "AllowDirectTeleport" boolean NOT NULL, + "RedirectGridX" int NOT NULL, + "RedirectGridY" int NOT NULL, + "ParentEstateID" int NOT NULL, + "SunPosition" double precision NOT NULL, + "EstateSkipScripts" boolean NOT NULL, + "BillableFactor" double precision NOT NULL, + "PublicAccess" boolean NOT NULL, + "AbuseEmail" varchar(255) NOT NULL, + "EstateOwner" varchar(36) NOT NULL, + "DenyMinors" boolean NOT NULL + ); + + +CREATE TABLE estate_map( + "RegionID" varchar(36) NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + "EstateID" int NOT NULL + ); + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +CREATE INDEX IX_estate_managers ON estate_managers + ( + "EstateID" + ); + + +CREATE INDEX IX_estate_groups ON estate_groups + ( + "EstateID" + ); + + +CREATE INDEX IX_estate_users ON estate_users + ( + "EstateID" + ); + +COMMIT; + +:VERSION 3 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_estateban + ( + "EstateID" int NOT NULL, + "bannedUUID" varchar(36) NOT NULL, + "bannedIp" varchar(16) NULL, + "bannedIpHostMask" varchar(16) NULL, + "bannedNameMask" varchar(64) NULL + ); + + INSERT INTO Tmp_estateban ("EstateID", "bannedUUID", "bannedIp", "bannedIpHostMask", "bannedNameMask") + SELECT "EstateID", "bannedUUID", "bannedIp", "bannedIpHostMask", "bannedNameMask" FROM estateban; + +DROP TABLE estateban; + +Alter table Tmp_estateban + rename to estateban; + +CREATE INDEX IX_estateban ON estateban + ( + "EstateID" + ); + +COMMIT; + + +:VERSION 4 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_estate_managers + ( + "EstateID" int NOT NULL, + uuid uuid NOT NULL + ); + +INSERT INTO Tmp_estate_managers ("EstateID", uuid) + SELECT "EstateID", cast(uuid as uuid) FROM estate_managers; + +DROP TABLE estate_managers; + +Alter table Tmp_estate_managers + rename to estate_managers; + +CREATE INDEX IX_estate_managers ON estate_managers + ( + "EstateID" + ); + +COMMIT; + + +:VERSION 5 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_estate_groups + ( + "EstateID" int NOT NULL, + uuid uuid NOT NULL + ) ; + + INSERT INTO Tmp_estate_groups ("EstateID", uuid) + SELECT "EstateID", cast(uuid as uuid) FROM estate_groups; + +DROP TABLE estate_groups; + +Alter table Tmp_estate_groups + rename to estate_groups; + +CREATE INDEX IX_estate_groups ON estate_groups + ( + "EstateID" + ); + +COMMIT; + + +:VERSION 6 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_estate_users + ( + "EstateID" int NOT NULL, + uuid uuid NOT NULL + ); + +INSERT INTO Tmp_estate_users ("EstateID", uuid) + SELECT "EstateID", cast(uuid as uuid) FROM estate_users ; + +DROP TABLE estate_users; + +Alter table Tmp_estate_users + rename to estate_users; + +CREATE INDEX IX_estate_users ON estate_users + ( + "EstateID" + ); + +COMMIT; + + +:VERSION 7 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_estateban + ( + "EstateID" int NOT NULL, + "bannedUUID" uuid NOT NULL, + "bannedIp" varchar(16) NULL, + "bannedIpHostMask" varchar(16) NULL, + "bannedNameMask" varchar(64) NULL + ); + +INSERT INTO Tmp_estateban ("EstateID", "bannedUUID", "bannedIp", "bannedIpHostMask", "bannedNameMask") + SELECT "EstateID", cast("bannedUUID" as uuid), "bannedIp", "bannedIpHostMask", "bannedNameMask" FROM estateban ; + +DROP TABLE estateban; + +Alter table Tmp_estateban + rename to estateban; + +CREATE INDEX IX_estateban ON estateban + ( + "EstateID" + ); + +COMMIT; + + +:VERSION 8 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_estate_settings + ( + "EstateID" integer default nextval('estate_settings_id') NOT NULL, + "EstateName" varchar(64) NULL DEFAULT (NULL), + "AbuseEmailToEstateOwner" boolean NOT NULL, + "DenyAnonymous" boolean NOT NULL, + "ResetHomeOnTeleport" boolean NOT NULL, + "FixedSun" boolean NOT NULL, + "DenyTransacted" boolean NOT NULL, + "BlockDwell" boolean NOT NULL, + "DenyIdentified" boolean NOT NULL, + "AllowVoice" boolean NOT NULL, + "UseGlobalTime" boolean NOT NULL, + "PricePerMeter" int NOT NULL, + "TaxFree" boolean NOT NULL, + "AllowDirectTeleport" boolean NOT NULL, + "RedirectGridX" int NOT NULL, + "RedirectGridY" int NOT NULL, + "ParentEstateID" int NOT NULL, + "SunPosition" double precision NOT NULL, + "EstateSkipScripts" boolean NOT NULL, + "BillableFactor" double precision NOT NULL, + "PublicAccess" boolean NOT NULL, + "AbuseEmail" varchar(255) NOT NULL, + "EstateOwner" uuid NOT NULL, + "DenyMinors" boolean NOT NULL + ); + +INSERT INTO Tmp_estate_settings ("EstateID", "EstateName", "AbuseEmailToEstateOwner", "DenyAnonymous", "ResetHomeOnTeleport", "FixedSun", "DenyTransacted", "BlockDwell", "DenyIdentified", "AllowVoice", "UseGlobalTime", "PricePerMeter", "TaxFree", "AllowDirectTeleport", "RedirectGridX", "RedirectGridY", "ParentEstateID", "SunPosition", "EstateSkipScripts", "BillableFactor", "PublicAccess", "AbuseEmail", "EstateOwner", "DenyMinors") + SELECT "EstateID", "EstateName", "AbuseEmailToEstateOwner", "DenyAnonymous", "ResetHomeOnTeleport", "FixedSun", "DenyTransacted", "BlockDwell", "DenyIdentified", "AllowVoice", "UseGlobalTime", "PricePerMeter", "TaxFree", "AllowDirectTeleport", "RedirectGridX", "RedirectGridY", "ParentEstateID", "SunPosition", "EstateSkipScripts", "BillableFactor", "PublicAccess", "AbuseEmail", cast("EstateOwner" as uuid), "DenyMinors" FROM estate_settings ; + +DROP TABLE estate_settings; + + +Alter table Tmp_estate_settings + rename to estate_settings; + + +Create index on estate_settings (lower("EstateName")); + +COMMIT; + + +:VERSION 9 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_estate_map + ( + "RegionID" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + "EstateID" int NOT NULL + ); + +INSERT INTO Tmp_estate_map ("RegionID", "EstateID") + SELECT cast("RegionID" as uuid), "EstateID" FROM estate_map ; + +DROP TABLE estate_map; + +Alter table Tmp_estate_map + rename to estate_map; + +COMMIT; + +:VERSION 10 + +BEGIN TRANSACTION; +ALTER TABLE estate_settings ADD COLUMN "AllowLandmark" boolean NOT NULL default true; +ALTER TABLE estate_settings ADD COLUMN "AllowParcelChanges" boolean NOT NULL default true; +ALTER TABLE estate_settings ADD COLUMN "AllowSetHome" boolean NOT NULL default true; +COMMIT; + +:VERSION 11 + +Begin transaction; + + +Commit; + diff --git a/OpenSim/Data/PGSQL/Resources/FriendsStore.migrations b/OpenSim/Data/PGSQL/Resources/FriendsStore.migrations new file mode 100644 index 0000000000..a87199bfcf --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/FriendsStore.migrations @@ -0,0 +1,44 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE Friends ( +"PrincipalID" uuid NOT NULL, +"Friend" varchar(255) NOT NULL, +"Flags" char(16) NOT NULL DEFAULT '0', +"Offered" varchar(32) NOT NULL DEFAULT 0); + + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +INSERT INTO Friends ("PrincipalID", "Friend", "Flags", "Offered") +SELECT "ownerID", "friendID", "friendPerms", 0 FROM userfriends; + +COMMIT; + +:VERSION 3 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_Friends + ("PrincipalID" varchar(255) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + "Friend" varchar(255) NOT NULL, + "Flags" char(16) NOT NULL DEFAULT '0', + "Offered" varchar(32) NOT NULL DEFAULT 0) ; + +INSERT INTO Tmp_Friends ("PrincipalID", "Friend", "Flags", "Offered") + SELECT cast("PrincipalID" as varchar(255)), "Friend", "Flags", "Offered" FROM Friends ; + +DROP TABLE Friends; + +Alter table Tmp_Friends + rename to Friends; + +ALTER TABLE Friends ADD PRIMARY KEY("PrincipalID", "Friend"); + + +COMMIT; diff --git a/OpenSim/Data/PGSQL/Resources/GridStore.migrations b/OpenSim/Data/PGSQL/Resources/GridStore.migrations new file mode 100644 index 0000000000..0ab8d2b6d0 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/GridStore.migrations @@ -0,0 +1,242 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE regions( + "regionHandle" varchar(255) NULL, + "regionName" varchar(255) NULL, + uuid varchar(255) NOT NULL PRIMARY KEY, + "regionRecvKey" varchar(255) NULL, + "regionSecret" varchar(255) NULL, + "regionSendKey" varchar(255) NULL, + "regionDataURI" varchar(255) NULL, + "serverIP" varchar(255) NULL, + "serverPort" varchar(255) NULL, + "serverURI" varchar(255) NULL, + "locX" varchar(255) NULL, + "locY" varchar(255) NULL, + "locZ" varchar(255) NULL, + "eastOverrideHandle" varchar(255) NULL, + "westOverrideHandle" varchar(255) NULL, + "southOverrideHandle" varchar(255) NULL, + "northOverrideHandle" varchar(255) NULL, + "regionAssetURI" varchar(255) NULL, + "regionAssetRecvKey" varchar(255) NULL, + "regionAssetSendKey" varchar(255) NULL, + "regionUserURI" varchar(255) NULL, + "regionUserRecvKey" varchar(255) NULL, + "regionUserSendKey" varchar(255) NULL, + "regionMapTexture" varchar(255) NULL, + "serverHttpPort" varchar(255) NULL, + "serverRemotingPort" varchar(255) NULL, + "owner_uuid" varchar(36) NULL +); + +COMMIT; + + +:VERSION 2 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_regions + ( + uuid varchar(36) NOT NULL, + "regionHandle" bigint NULL, + "regionName" varchar(20) NULL, + "regionRecvKey" varchar(128) NULL, + "regionSendKey" varchar(128) NULL, + "regionSecret" varchar(128) NULL, + "regionDataURI" varchar(128) NULL, + "serverIP" varchar(64) NULL, + "serverPort" int NULL, + "serverURI" varchar(255) NULL, + "locX" int NULL, + "locY" int NULL, + "locZ" int NULL, + "eastOverrideHandle" bigint NULL, + "westOverrideHandle" bigint NULL, + "southOverrideHandle" bigint NULL, + "northOverrideHandle" bigint NULL, + "regionAssetURI" varchar(255) NULL, + "regionAssetRecvKey" varchar(128) NULL, + "regionAssetSendKey" varchar(128) NULL, + "regionUserURI" varchar(255) NULL, + "regionUserRecvKey" varchar(128) NULL, + "regionUserSendKey" varchar(128) NULL, + "regionMapTexture" varchar(36) NULL, + "serverHttpPort" int NULL, + "serverRemotingPort" int NULL, + "owner_uuid" varchar(36) NULL, + "originUUID" varchar(36) NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000') + ); + +INSERT INTO Tmp_regions (uuid, "regionHandle", "regionName", "regionRecvKey", "regionSendKey", "regionSecret", "regionDataURI", "serverIP", "serverPort", "serverURI", "locX", "locY", "locZ", "eastOverrideHandle", "westOverrideHandle", "southOverrideHandle", "northOverrideHandle", "regionAssetURI", "regionAssetRecvKey", "regionAssetSendKey", "regionUserURI", "regionUserRecvKey", "regionUserSendKey", "regionMapTexture", "serverHttpPort", "serverRemotingPort", "owner_uuid") + SELECT cast(uuid as varchar(36)), cast("regionHandle" as bigint), cast("regionName" as varchar(20)), cast("regionRecvKey" as varchar(128)), cast("regionSendKey" as varchar(128)), cast("regionSecret" as varchar(128)), cast("regionDataURI" as varchar(128)), cast("serverIP" as varchar(64)), cast("serverPort" as int), "serverURI", cast("locX" as int), cast("locY" as int), cast("locZ" as int), cast("eastOverrideHandle" as bigint), cast("westOverrideHandle" as bigint), + cast("southOverrideHandle" as bigint), cast("northOverrideHandle" as bigint), "regionAssetURI", cast("regionAssetRecvKey" as varchar(128)), cast("regionAssetSendKey" as varchar(128)), "regionUserURI", cast("regionUserRecvKey" as varchar(128)), cast("regionUserSendKey" as varchar(128)), cast("regionMapTexture" as varchar(36)), + cast("serverHttpPort" as int), cast("serverRemotingPort" as int), "owner_uuid" + FROM regions; + +DROP TABLE regions; + +alter table Tmp_regions + rename to regions; + +COMMIT; + +:VERSION 3 + +BEGIN TRANSACTION; + +CREATE INDEX IX_regions_name ON regions + ( + "regionName" + ); + +CREATE INDEX IX_regions_handle ON regions + ( + "regionHandle" + ); + + +CREATE INDEX IX_regions_override ON regions + ( + "eastOverrideHandle", + "westOverrideHandle", + "southOverrideHandle", + "northOverrideHandle" + ); + +COMMIT; + + +:VERSION 4 + +/* To prevent any potential data loss issues, you should review this script in detail before running it outside the cotext of the database designer.*/ +BEGIN TRANSACTION; + +CREATE TABLE Tmp_regions + ( + uuid uuid NOT NULL, + "regionHandle" bigint NULL, + "regionName" varchar(20) NULL, + "regionRecvKey" varchar(128) NULL, + "regionSendKey" varchar(128) NULL, + "regionSecret" varchar(128) NULL, + "regionDataURI" varchar(128) NULL, + "serverIP" varchar(64) NULL, + "serverPort" int NULL, + "serverURI" varchar(255) NULL, + "locX" int NULL, + "locY" int NULL, + "locZ" int NULL, + "eastOverrideHandle" bigint NULL, + "westOverrideHandle" bigint NULL, + "southOverrideHandle" bigint NULL, + "northOverrideHandle" bigint NULL, + "regionAssetURI" varchar(255) NULL, + "regionAssetRecvKey" varchar(128) NULL, + "regionAssetSendKey" varchar(128) NULL, + "regionUserURI" varchar(255) NULL, + "regionUserRecvKey" varchar(128) NULL, + "regionUserSendKey" varchar(128) NULL, + "regionMapTexture" uuid NULL, + "serverHttpPort" int NULL, + "serverRemotingPort" int NULL, + "owner_uuid" uuid NOT NULL, + "originUUID" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000') + ); + + +INSERT INTO Tmp_regions (uuid, "regionHandle", "regionName", "regionRecvKey", "regionSendKey", "regionSecret", "regionDataURI", "serverIP", "serverPort", "serverURI", "locX", "locY", "locZ", "eastOverrideHandle", "westOverrideHandle", "southOverrideHandle", "northOverrideHandle", "regionAssetURI", "regionAssetRecvKey", "regionAssetSendKey", "regionUserURI", "regionUserRecvKey", "regionUserSendKey", "regionMapTexture", "serverHttpPort", "serverRemotingPort", "owner_uuid", "originUUID") + SELECT cast(uuid as uuid), "regionHandle", "regionName", "regionRecvKey", "regionSendKey", "regionSecret", "regionDataURI", "serverIP", "serverPort", "serverURI", "locX", "locY", "locZ", "eastOverrideHandle", "westOverrideHandle", "southOverrideHandle", "northOverrideHandle", "regionAssetURI", "regionAssetRecvKey", "regionAssetSendKey", "regionUserURI", "regionUserRecvKey", "regionUserSendKey", cast("regionMapTexture" as uuid), "serverHttpPort", "serverRemotingPort", cast( "owner_uuid" as uuid), cast("originUUID" as uuid) FROM regions ; + + +DROP TABLE regions; + +alter table Tmp_regions rename to regions; + +ALTER TABLE regions ADD CONSTRAINT + PK__regions__uuid PRIMARY KEY + ( + uuid + ); + +CREATE INDEX IX_regions_name ON regions + ( + "regionName" + ); + +CREATE INDEX IX_regions_handle ON regions + ( + "regionHandle" + ); + +CREATE INDEX IX_regions_override ON regions + ( + "eastOverrideHandle", + "westOverrideHandle", + "southOverrideHandle", + "northOverrideHandle" + ); + +COMMIT; + + +:VERSION 5 + +BEGIN TRANSACTION; + +ALTER TABLE regions ADD access int default 0; + +COMMIT; + + +:VERSION 6 + +BEGIN TRANSACTION; + +ALTER TABLE regions ADD "ScopeID" uuid default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE regions alter column "owner_uuid" set DEFAULT ('00000000-0000-0000-0000-000000000000'); +ALTER TABLE regions ADD "sizeX" integer not null default 0; +ALTER TABLE regions ADD "sizeY" integer not null default 0; + +COMMIT; + + +:VERSION 7 + +BEGIN TRANSACTION; + +ALTER TABLE regions ADD "flags" integer NOT NULL DEFAULT 0; +CREATE INDEX flags ON regions("flags"); +ALTER TABLE regions ADD "last_seen" integer NOT NULL DEFAULT 0; +ALTER TABLE regions ADD "PrincipalID" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; +ALTER TABLE regions ADD "Token" varchar(255) NOT NULL DEFAULT 0; + +COMMIT; + +:VERSION 8 + +BEGIN TRANSACTION; +ALTER TABLE regions ALTER COLUMN "regionName" type VarChar(128) ; + +DROP INDEX IX_regions_name; +ALTER TABLE regions ALTER COLUMN "regionName" type VarChar(128), + ALTER COLUMN "regionName" SET NOT NULL; + +CREATE INDEX IX_regions_name ON regions + ( + "regionName" + ); + +COMMIT; + +:VERSION 9 + +BEGIN TRANSACTION; + +ALTER TABLE regions ADD "parcelMapTexture" uuid NULL; + +COMMIT; + diff --git a/OpenSim/Data/PGSQL/Resources/GridUserStore.migrations b/OpenSim/Data/PGSQL/Resources/GridUserStore.migrations new file mode 100644 index 0000000000..d37c4f6d72 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/GridUserStore.migrations @@ -0,0 +1,60 @@ +:VERSION 1 # -------------------------- + +BEGIN TRANSACTION; + +CREATE TABLE GridUser ( + "UserID" VARCHAR(255) NOT NULL Primary Key, + "HomeRegionID" CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + "HomePosition" CHAR(64) NOT NULL DEFAULT '<0,0,0>', + "HomeLookAt" CHAR(64) NOT NULL DEFAULT '<0,0,0>', + "LastRegionID" CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + "LastPosition" CHAR(64) NOT NULL DEFAULT '<0,0,0>', + "LastLookAt" CHAR(64) NOT NULL DEFAULT '<0,0,0>', + "Online" CHAR(5) NOT NULL DEFAULT 'false', + "Login" CHAR(16) NOT NULL DEFAULT '0', + "Logout" CHAR(16) NOT NULL DEFAULT '0' +) ; + +COMMIT; + +:VERSION 2 # -------------------------- + +BEGIN TRANSACTION; + +CREATE TABLE GridUser_tmp ( + "UserID" VARCHAR(255) NOT NULL PRIMARY KEY, + "HomeRegionID" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + "HomePosition" CHAR(64) NOT NULL DEFAULT '<0,0,0>', + "HomeLookAt" CHAR(64) NOT NULL DEFAULT '<0,0,0>', + "LastRegionID" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + "LastPosition" CHAR(64) NOT NULL DEFAULT '<0,0,0>', + "LastLookAt" CHAR(64) NOT NULL DEFAULT '<0,0,0>', + "Online" CHAR(5) NOT NULL DEFAULT 'false', + "Login" CHAR(16) NOT NULL DEFAULT '0', + "Logout" CHAR(16) NOT NULL DEFAULT '0' + ); + +COMMIT; + + +INSERT INTO GridUser_tmp ("UserID" + ,"HomeRegionID" + ,"HomePosition" + ,"HomeLookAt" + ,"LastRegionID" + ,"LastPosition" + ,"LastLookAt" + ,"Online" + ,"Login" + ,"Logout") + SELECT "UserID", cast("HomeRegionID" as uuid), "HomePosition" ,"HomeLookAt" , cast("LastRegionID" as uuid), + "LastPosition" + ,"LastLookAt" + ,"Online" + ,"Login" + ,"Logout" FROM GridUser; + +DROP TABLE GridUser; + +alter table GridUser_tmp rename to GridUser; + diff --git a/OpenSim/Data/PGSQL/Resources/HGTravelStore.migrations b/OpenSim/Data/PGSQL/Resources/HGTravelStore.migrations new file mode 100644 index 0000000000..adf126d7c3 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/HGTravelStore.migrations @@ -0,0 +1,17 @@ +:VERSION 1 # -------------------------- + +BEGIN; + +CREATE TABLE hg_traveling_data ( + "SessionID" VARCHAR(36) NOT NULL Primary Key, + "UserID" VARCHAR(36) NOT NULL, + "GridExternalName" VARCHAR(255) NOT NULL DEFAULT '', + "ServiceToken" VARCHAR(255) NOT NULL DEFAULT '', + "ClientIPAddress" VARCHAR(16) NOT NULL DEFAULT '', + "MyIPAddress" VARCHAR(16) NOT NULL DEFAULT '', + "TMStamp" timestamp NOT NULL default now() +); + + +COMMIT; + diff --git a/OpenSim/Data/PGSQL/Resources/IM_Store.migrations b/OpenSim/Data/PGSQL/Resources/IM_Store.migrations new file mode 100644 index 0000000000..70dc0119d5 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/IM_Store.migrations @@ -0,0 +1,26 @@ +:VERSION 1 # -------------------------- + +BEGIN Transaction; + +Create Sequence im_offiline_id increment by 1 start with 1; + +CREATE TABLE im_offline ( + "ID" integer PRIMARY KEY NOT NULL DEFAULT nextval('im_offiline_id') , + "PrincipalID" char(36) NOT NULL default '', + "Message" text NOT NULL, + "TMStamp" timestamp NOT NULL default now() +); + +COMMIT; + +:VERSION 2 # -------------------------- + +BEGIN; + +/* +INSERT INTO `im_offline` SELECT * from `diva_im_offline`; +DROP TABLE `diva_im_offline`; +DELETE FROM `migrations` WHERE name='diva_im_Store'; +*/ + +COMMIT; diff --git a/OpenSim/Data/PGSQL/Resources/InventoryStore.migrations b/OpenSim/Data/PGSQL/Resources/InventoryStore.migrations new file mode 100644 index 0000000000..b61e1f8753 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/InventoryStore.migrations @@ -0,0 +1,211 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE inventoryfolders ( + "folderID" varchar(36) NOT NULL default '' PRIMARY KEY, + "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 +); + + +CREATE INDEX owner ON inventoryfolders +( + "agentID" ASC +); + +CREATE INDEX parent ON inventoryfolders +( + "parentFolderID" ASC +); + + +CREATE TABLE inventoryitems ( + "inventoryID" varchar(36) NOT NULL default '' Primary Key, + "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, + "salePrice" int default NULL, + "saleType" smallint default NULL, + "creationDate" int default NULL, + "groupID" varchar(36) default NULL, + "groupOwned" boolean default NULL, + "flags" int default NULL +); + + +CREATE INDEX ii_owner ON inventoryitems +( + "avatarID" ASC +); + +CREATE INDEX ii_folder ON inventoryitems +( + "parentFolderID" ASC +); + +COMMIT; + + +:VERSION 2 + +BEGIN TRANSACTION; + +ALTER TABLE inventoryitems ADD "inventoryGroupPermissions" INTEGER NOT NULL default 0; + +COMMIT; + +:VERSION 3 + +/* To prevent any potential data loss issues, you should review this script in detail before running it outside the cotext of the database designer.*/ +BEGIN TRANSACTION; + +CREATE TABLE Tmp_inventoryfolders + ( + "folderID" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + "agentID" uuid NULL DEFAULT (NULL), + "parentFolderID" uuid NULL DEFAULT (NULL), + "folderName" varchar(64) NULL DEFAULT (NULL), + "type" smallint NOT NULL DEFAULT ((0)), + "version" int NOT NULL DEFAULT ((0)) + ); + + INSERT INTO Tmp_inventoryfolders ("folderID", "agentID", "parentFolderID", "folderName", type, version) + SELECT cast("folderID" as uuid), cast("agentID" as uuid), cast("parentFolderID" as uuid), "folderName", "type", "version" + FROM inventoryfolders; + +DROP TABLE inventoryfolders; + +alter table Tmp_inventoryfolders rename to inventoryfolders; + +ALTER TABLE inventoryfolders ADD CONSTRAINT + PK__inventor__C2FABFB3173876EA PRIMARY KEY + ( + "folderID" + ); + +CREATE INDEX owner ON inventoryfolders + ( + "agentID" + ); + +CREATE INDEX parent ON inventoryfolders + ( + "parentFolderID" + ); + +COMMIT; + + +:VERSION 4 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_inventoryitems + ( + "inventoryID" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + "assetID" uuid NULL DEFAULT (NULL), + "assetType" int NULL DEFAULT (NULL), + "parentFolderID" uuid NULL DEFAULT (NULL), + "avatarID" uuid NULL DEFAULT (NULL), + "inventoryName" varchar(64) NULL DEFAULT (NULL), + "inventoryDescription" varchar(128) NULL DEFAULT (NULL), + "inventoryNextPermissions" int NULL DEFAULT (NULL), + "inventoryCurrentPermissions" int NULL DEFAULT (NULL), + "invType" int NULL DEFAULT (NULL), + "creatorID" uuid NULL DEFAULT (NULL), + "inventoryBasePermissions" int NOT NULL DEFAULT ((0)), + "inventoryEveryOnePermissions" int NOT NULL DEFAULT ((0)), + "salePrice" int NULL DEFAULT (NULL), + "SaleType" smallint NULL DEFAULT (NULL), + "creationDate" int NULL DEFAULT (NULL), + "groupID" uuid NULL DEFAULT (NULL), + "groupOwned" boolean NULL DEFAULT (NULL), + "flags" int NULL DEFAULT (NULL), + "inventoryGroupPermissions" int NOT NULL DEFAULT ((0)) + ); + + + INSERT INTO Tmp_inventoryitems ("inventoryID", "assetID", "assetType", "parentFolderID", "avatarID", "inventoryName", "inventoryDescription", "inventoryNextPermissions", "inventoryCurrentPermissions", "invType", "creatorID", "inventoryBasePermissions", "inventoryEveryOnePermissions", "salePrice", "SaleType", "creationDate", "groupID", "groupOwned", "flags", "inventoryGroupPermissions") + SELECT cast("inventoryID" as uuid), cast("assetID" as uuid), "assetType", cast("parentFolderID" as uuid), cast("avatarID" as uuid), "inventoryName", "inventoryDescription", "inventoryNextPermissions", "inventoryCurrentPermissions", "invType", cast("creatorID" as uuid), "inventoryBasePermissions", "inventoryEveryOnePermissions", "salePrice", "SaleType", "creationDate", cast("groupID" as uuid), "groupOwned", "flags", "inventoryGroupPermissions" + FROM inventoryitems ; + +DROP TABLE inventoryitems; + +alter table Tmp_inventoryitems rename to inventoryitems; + +ALTER TABLE inventoryitems ADD CONSTRAINT + PK__inventor__C4B7BC2220C1E124 PRIMARY KEY + ( + "inventoryID" + ); + + +CREATE INDEX ii2_owner ON inventoryitems + ( + "avatarID" + ); + +CREATE INDEX ii2_folder ON inventoryitems + ( + "parentFolderID" + ); + +COMMIT; + +:VERSION 5 + + +BEGIN TRANSACTION; + +-- # Restoring defaults: +-- # NOTE: "inventoryID" does NOT need one: it's NOT NULL PK and a unique Guid must be provided every time anyway! + +alter table inventoryitems + alter column "inventoryBasePermissions" set default 0; +alter table inventoryitems + alter column "inventoryEveryOnePermissions" set default 0; +alter table inventoryitems + alter column "inventoryGroupPermissions" set default 0 ; + +COMMIT ; + +:VERSION 7 + +BEGIN TRANSACTION; + +-- # "creatorID" goes back to VARCHAR(36) (???) + +alter table inventoryitems + alter column "creatorID" type varchar(36); + +COMMIT ; + +:VERSION 8 + +ALTER TABLE inventoryitems + alter column "creatorID" set DEFAULT '00000000-0000-0000-0000-000000000000'; + + +:VERSION 9 + +BEGIN TRANSACTION; + +--# "creatorID" goes up to VARCHAR(255) + +alter table inventoryitems + alter column "creatorID" type varchar(255); + +Commit; diff --git a/OpenSim/Data/PGSQL/Resources/LogStore.migrations b/OpenSim/Data/PGSQL/Resources/LogStore.migrations new file mode 100644 index 0000000000..83727c6fd5 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/LogStore.migrations @@ -0,0 +1,16 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE logs ( + "logID" int NOT NULL Primary Key, + "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" text +); + +COMMIT; + diff --git a/OpenSim/Data/PGSQL/Resources/Presence.migrations b/OpenSim/Data/PGSQL/Resources/Presence.migrations new file mode 100644 index 0000000000..684faa2717 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/Presence.migrations @@ -0,0 +1,30 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE Presence ( +"UserID" varchar(255) NOT NULL, +"RegionID" uuid NOT NULL, +"SessionID" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', +"SecureSessionID" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000' +); + + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +CREATE UNIQUE INDEX SessionID ON Presence("SessionID"); +CREATE INDEX UserID ON Presence("UserID"); + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +ALTER TABLE Presence ADD "LastSeen" Timestamp; + +COMMIT; diff --git a/OpenSim/Data/PGSQL/Resources/RegionStore.migrations b/OpenSim/Data/PGSQL/Resources/RegionStore.migrations new file mode 100644 index 0000000000..65eb011989 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/RegionStore.migrations @@ -0,0 +1,1136 @@ +begin transaction ; +:VERSION 1 + +CREATE TABLE prims( + "UUID" varchar(255) NOT NULL Primary key, + "RegionUUID" varchar(255) NULL, + "ParentID" int NULL, + "CreationDate" int NULL, + "Name" varchar(255) NULL, + "SceneGroupID" varchar(255) NULL, + "Text" varchar(255) NULL, + "Description" varchar(255) NULL, + "SitName" varchar(255) NULL, + "TouchName" varchar(255) NULL, + "ObjectFlags" int NULL, + "CreatorID" varchar(255) NULL, + "OwnerID" varchar(255) NULL, + "GroupID" varchar(255) NULL, + "LastOwnerID" varchar(255) NULL, + "OwnerMask" int NULL, + "NextOwnerMask" int NULL, + "GroupMask" int NULL, + "EveryoneMask" int NULL, + "BaseMask" int NULL, + "PositionX" double precision NULL, + "PositionY" double precision NULL, + "PositionZ" double precision NULL, + "GroupPositionX" double precision NULL, + "GroupPositionY" double precision NULL, + "GroupPositionZ" double precision NULL, + "VelocityX" double precision NULL, + "VelocityY" double precision NULL, + "VelocityZ" double precision NULL, + "AngularVelocityX" double precision NULL, + "AngularVelocityY" double precision NULL, + "AngularVelocityZ" double precision NULL, + "AccelerationX" double precision NULL, + "AccelerationY" double precision NULL, + "AccelerationZ" double precision NULL, + "RotationX" double precision NULL, + "RotationY" double precision NULL, + "RotationZ" double precision NULL, + "RotationW" double precision NULL, + "SitTargetOffsetX" double precision NULL, + "SitTargetOffsetY" double precision NULL, + "SitTargetOffsetZ" double precision NULL, + "SitTargetOrientW" double precision NULL, + "SitTargetOrientX" double precision NULL, + "SitTargetOrientY" double precision NULL, + "SitTargetOrientZ" double precision NULL + ); + +CREATE TABLE primshapes( + "UUID" varchar(255) NOT NULL primary key, + "Shape" int NULL, + "ScaleX" double precision NULL, + "ScaleY" double precision NULL, + "ScaleZ" double precision NULL, + "PCode" int NULL, + "PathBegin" int NULL, + "PathEnd" int NULL, + "PathScaleX" int NULL, + "PathScaleY" int NULL, + "PathShearX" int NULL, + "PathShearY" int NULL, + "PathSkew" int NULL, + "PathCurve" int NULL, + "PathRadiusOffset" int NULL, + "PathRevolutions" int NULL, + "PathTaperX" int NULL, + "PathTaperY" int NULL, + "PathTwist" int NULL, + "PathTwistBegin" int NULL, + "ProfileBegin" int NULL, + "ProfileEnd" int NULL, + "ProfileCurve" int NULL, + "ProfileHollow" int NULL, + "State" int NULL, + "Texture" bytea NULL, + "ExtraParams" bytea NULL + ); + +CREATE TABLE primitems( + "itemID" varchar(255) NOT NULL primary key, + "primID" varchar(255) NULL, + "assetID" varchar(255) NULL, + "parentFolderID" varchar(255) NULL, + "invType" int NULL, + "assetType" int NULL, + "name" varchar(255) NULL, + "description" varchar(255) NULL, + "creationDate" varchar(255) NULL, + "creatorID" varchar(255) NULL, + "ownerID" varchar(255) NULL, + "lastOwnerID" varchar(255) NULL, + "groupID" varchar(255) NULL, + "nextPermissions" int NULL, + "currentPermissions" int NULL, + "basePermissions" int NULL, + "everyonePermissions" int NULL, + "groupPermissions" int NULL + ); + +CREATE TABLE terrain( + "RegionUUID" varchar(255) NULL, + "Revision" int NULL, + "Heightfield" bytea NULL +); + + +CREATE TABLE land( + "UUID" varchar(255) NOT NULL primary key, + "RegionUUID" varchar(255) NULL, + "LocalLandID" int NULL, + "Bitmap" bytea NULL, + "Name" varchar(255) NULL, + "Description" varchar(255) NULL, + "OwnerUUID" varchar(255) NULL, + "IsGroupOwned" boolean NULL, + "Area" int NULL, + "AuctionID" int NULL, + "Category" int NULL, + "ClaimDate" int NULL, + "ClaimPrice" int NULL, + "GroupUUID" varchar(255) NULL, + "SalePrice" int NULL, + "LandStatus" int NULL, + "LandFlags" int NULL, + "LandingType" int NULL, + "MediaAutoScale" int NULL, + "MediaTextureUUID" varchar(255) NULL, + "MediaURL" varchar(255) NULL, + "MusicURL" varchar(255) NULL, + "PassHours" double precision NULL, + "PassPrice" int NULL, + "SnapshotUUID" varchar(255) NULL, + "UserLocationX" double precision NULL, + "UserLocationY" double precision NULL, + "UserLocationZ" double precision NULL, + "UserLookAtX" double precision NULL, + "UserLookAtY" double precision NULL, + "UserLookAtZ" double precision NULL +); + +Create index on land (lower("Name")); + +CREATE TABLE landaccesslist( + "LandUUID" varchar(255) NULL, + "AccessUUID" varchar(255) NULL, + "Flags" int NULL +); + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +CREATE TABLE regionban ( + "regionUUID" VARCHAR(36) NOT NULL, + "bannedUUID" VARCHAR(36) NOT NULL, + "bannedIp" VARCHAR(16) NOT NULL, + "bannedIpHostMask" VARCHAR(16) NOT NULL + ); + +create table regionsettings ( + "regionUUID" varchar(36) not null primary key, + "block_terraform" boolean not null, + "block_fly" boolean not null, + "allow_damage" boolean not null, + "restrict_pushing" boolean not null, + "allow_land_resell" boolean not null, + "allow_land_join_divide" boolean not null, + "block_show_in_search" boolean not null, + "agent_limit" int not null, + "object_bonus" double precision not null, + "maturity" int not null, + "disable_scripts" boolean not null, + "disable_collisions" boolean not null, + "disable_physics" boolean not null, + "terrain_texture_1" varchar(36) not null, + "terrain_texture_2" varchar(36) not null, + "terrain_texture_3" varchar(36) not null, + "terrain_texture_4" varchar(36) not null, + "elevation_1_nw" double precision not null, + "elevation_2_nw" double precision not null, + "elevation_1_ne" double precision not null, + "elevation_2_ne" double precision not null, + "elevation_1_se" double precision not null, + "elevation_2_se" double precision not null, + "elevation_1_sw" double precision not null, + "elevation_2_sw" double precision not null, + "water_height" double precision not null, + "terrain_raise_limit" double precision not null, + "terrain_lower_limit" double precision not null, + "use_estate_sun" boolean not null, + "fixed_sun" boolean not null, + "sun_position" double precision not null, + "covenant" varchar(36) default NULL, + "Sandbox" boolean NOT NULL + ); + +COMMIT; + +:VERSION 3 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_prims + ( + "UUID" varchar(36) NOT NULL , + "RegionUUID" varchar(36) NULL, + "ParentID" int NULL, + "CreationDate" int NULL, + "Name" varchar(255) NULL, + "SceneGroupID" varchar(36) NULL, + "Text" varchar(255) NULL, + "Description" varchar(255) NULL, + "SitName" varchar(255) NULL, + "TouchName" varchar(255) NULL, + "ObjectFlags" int NULL, + "CreatorID" varchar(36) NULL, + "OwnerID" varchar(36) NULL, + "GroupID" varchar(36) NULL, + "LastOwnerID" varchar(36) NULL, + "OwnerMask" int NULL, + "NextOwnerMask" int NULL, + "GroupMask" int NULL, + "EveryoneMask" int NULL, + "BaseMask" int NULL, + "PositionX" double precision NULL, + "PositionY" double precision NULL, + "PositionZ" double precision NULL, + "GroupPositionX" double precision NULL, + "GroupPositionY" double precision NULL, + "GroupPositionZ" double precision NULL, + "VelocityX" double precision NULL, + "VelocityY" double precision NULL, + "VelocityZ" double precision NULL, + "AngularVelocityX" double precision NULL, + "AngularVelocityY" double precision NULL, + "AngularVelocityZ" double precision NULL, + "AccelerationX" double precision NULL, + "AccelerationY" double precision NULL, + "AccelerationZ" double precision NULL, + "RotationX" double precision NULL, + "RotationY" double precision NULL, + "RotationZ" double precision NULL, + "RotationW" double precision NULL, + "SitTargetOffsetX" double precision NULL, + "SitTargetOffsetY" double precision NULL, + "SitTargetOffsetZ" double precision NULL, + "SitTargetOrientW" double precision NULL, + "SitTargetOrientX" double precision NULL, + "SitTargetOrientY" double precision NULL, + "SitTargetOrientZ" double precision NULL + ); + +INSERT INTO Tmp_prims ("UUID", "RegionUUID", "ParentID", "CreationDate", "Name", "SceneGroupID", "Text", "Description", "SitName", "TouchName", "ObjectFlags", "CreatorID", "OwnerID", "GroupID", "LastOwnerID", "OwnerMask", "NextOwnerMask", "GroupMask", "EveryoneMask", "BaseMask", "PositionX", "PositionY", "PositionZ", "GroupPositionX", "GroupPositionY", "GroupPositionZ", "VelocityX", "VelocityY", "VelocityZ", "AngularVelocityX", "AngularVelocityY", "AngularVelocityZ", "AccelerationX", "AccelerationY", "AccelerationZ", "RotationX", "RotationY", "RotationZ", "RotationW", "SitTargetOffsetX", "SitTargetOffsetY", "SitTargetOffsetZ", "SitTargetOrientW", "SitTargetOrientX", "SitTargetOrientY", "SitTargetOrientZ") + SELECT cast("UUID" as varchar(36)), cast("RegionUUID" as varchar(36)), "ParentID", "CreationDate", "Name", cast("SceneGroupID" as varchar(36)), "Text", "Description", "SitName", "TouchName", "ObjectFlags", cast("CreatorID" as varchar(36)), cast("OwnerID" as varchar(36)), cast( "GroupID" as varchar(36)), cast("LastOwnerID" as varchar(36)), "OwnerMask", "NextOwnerMask", "GroupMask", "EveryoneMask", "BaseMask", "PositionX", "PositionY", "PositionZ", "GroupPositionX", "GroupPositionY", "GroupPositionZ", "VelocityX", "VelocityY", "VelocityZ", "AngularVelocityX", "AngularVelocityY", "AngularVelocityZ", "AccelerationX", "AccelerationY", "AccelerationZ", "RotationX", "RotationY", "RotationZ", "RotationW", "SitTargetOffsetX", "SitTargetOffsetY", "SitTargetOffsetZ", "SitTargetOrientW", "SitTargetOrientX", "SitTargetOrientY", "SitTargetOrientZ" + FROM prims ; + +DROP TABLE prims; + +alter table Tmp_prims rename to prims; + + +ALTER TABLE prims ADD CONSTRAINT + PK__prims__10566F31 PRIMARY KEY + ( + "UUID" + ); + +COMMIT; + +:VERSION 4 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_primitems + ( + "itemID" varchar(36) NOT NULL, + "primID" varchar(36) NULL, + "assetID" varchar(36) NULL, + "parentFolderID" varchar(36) NULL, + "invType" int NULL, + "assetType" int NULL, + "name" varchar(255) NULL, + "description" varchar(255) NULL, + "creationDate" varchar(255) NULL, + "creatorID" varchar(36) NULL, + "ownerID" varchar(36) NULL, + "lastOwnerID" varchar(36) NULL, + "groupID" varchar(36) NULL, + "nextPermissions" int NULL, + "currentPermissions" int NULL, + "basePermissions" int NULL, + "everyonePermissions" int NULL, + "groupPermissions" int NULL + ); + +INSERT INTO Tmp_primitems ("itemID", "primID", "assetID", "parentFolderID", "invType", "assetType", "name", "description", "creationDate", "creatorID", "ownerID", "lastOwnerID", "groupID", "nextPermissions", "currentPermissions", "basePermissions", "everyonePermissions", "groupPermissions") + SELECT cast("itemID" as varchar(36)), cast("primID" as varchar(36)), cast("assetID" as varchar(36)), cast( "parentFolderID" as varchar(36)), "invType", "assetType", "name", "description", "creationDate", cast( "creatorID" as varchar(36)), cast("ownerID" as varchar(36)), cast("lastOwnerID" as varchar(36)), cast("groupID" as varchar(36)), "nextPermissions", "currentPermissions", "basePermissions", "everyonePermissions", "groupPermissions" + from primitems; + +DROP TABLE primitems; + +alter table Tmp_primitems rename to primitems; + +ALTER TABLE primitems ADD CONSTRAINT + PK__primitems__0A688BB1 PRIMARY KEY + ( + "itemID" + ); + + +COMMIT; + + +:VERSION 5 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_primshapes + ( + "UUID" varchar(36) NOT NULL, + "Shape" int NULL, + "ScaleX" double precision NULL, + "ScaleY" double precision NULL, + "ScaleZ" double precision NULL, + "PCode" int NULL, + "PathBegin" int NULL, + "PathEnd" int NULL, + "PathScaleX" int NULL, + "PathScaleY" int NULL, + "PathShearX" int NULL, + "PathShearY" int NULL, + "PathSkew" int NULL, + "PathCurve" int NULL, + "PathRadiusOffset" int NULL, + "PathRevolutions" int NULL, + "PathTaperX" int NULL, + "PathTaperY" int NULL, + "PathTwist" int NULL, + "PathTwistBegin" int NULL, + "ProfileBegin" int NULL, + "ProfileEnd" int NULL, + "ProfileCurve" int NULL, + "ProfileHollow" int NULL, + "State" int NULL, + "Texture" bytea NULL, + "ExtraParams" bytea NULL + ) ; + +INSERT INTO Tmp_primshapes ("UUID", "Shape", "ScaleX", "ScaleY", "ScaleZ", "PCode", "PathBegin", "PathEnd", "PathScaleX", "PathScaleY", "PathShearX", "PathShearY", "PathSkew", "PathCurve", "PathRadiusOffset", "PathRevolutions", "PathTaperX", "PathTaperY", "PathTwist", "PathTwistBegin", "ProfileBegin", "ProfileEnd", "ProfileCurve", "ProfileHollow", "State", "Texture", "ExtraParams") + SELECT cast("UUID" as varchar(36)), "Shape", "ScaleX", "ScaleY", "ScaleZ", "PCode", "PathBegin", "PathEnd", "PathScaleX", "PathScaleY", "PathShearX", "PathShearY", "PathSkew", "PathCurve", "PathRadiusOffset", "PathRevolutions", "PathTaperX", "PathTaperY", "PathTwist", "PathTwistBegin", "ProfileBegin", "ProfileEnd", "ProfileCurve", "ProfileHollow", "State", "Texture", "ExtraParams" + FROM primshapes; + +DROP TABLE primshapes; + +alter table Tmp_primshapes rename to primshapes; + +ALTER TABLE primshapes ADD CONSTRAINT + PK__primshapes__0880433F PRIMARY KEY + ( + "UUID" + ) ; + +COMMIT; + + +:VERSION 6 + +BEGIN TRANSACTION; + +ALTER TABLE prims ADD "PayPrice" int not null default 0; +ALTER TABLE prims ADD "PayButton1" int not null default 0; +ALTER TABLE prims ADD "PayButton2" int not null default 0; +ALTER TABLE prims ADD "PayButton3" int not null default 0; +ALTER TABLE prims ADD "PayButton4" int not null default 0; +ALTER TABLE prims ADD "LoopedSound" varchar(36) not null default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE prims ADD "LoopedSoundGain" double precision not null default 0.0; +ALTER TABLE prims ADD "TextureAnimation" bytea; +ALTER TABLE prims ADD "OmegaX" double precision not null default 0.0; +ALTER TABLE prims ADD "OmegaY" double precision not null default 0.0; +ALTER TABLE prims ADD "OmegaZ" double precision not null default 0.0; +ALTER TABLE prims ADD "CameraEyeOffsetX" double precision not null default 0.0; +ALTER TABLE prims ADD "CameraEyeOffsetY" double precision not null default 0.0; +ALTER TABLE prims ADD "CameraEyeOffsetZ" double precision not null default 0.0; +ALTER TABLE prims ADD "CameraAtOffsetX" double precision not null default 0.0; +ALTER TABLE prims ADD "CameraAtOffsetY" double precision not null default 0.0; +ALTER TABLE prims ADD "CameraAtOffsetZ" double precision not null default 0.0; +ALTER TABLE prims ADD "ForceMouselook" smallint not null default 0; +ALTER TABLE prims ADD "ScriptAccessPin" int not null default 0; +ALTER TABLE prims ADD "AllowedDrop" smallint not null default 0; +ALTER TABLE prims ADD "DieAtEdge" smallint not null default 0; +ALTER TABLE prims ADD "SalePrice" int not null default 10; +ALTER TABLE prims ADD "SaleType" smallint not null default 0; + +ALTER TABLE primitems add "flags" integer not null default 0; + +ALTER TABLE land ADD "AuthbuyerID" varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; + +CREATE index prims_regionuuid on prims("RegionUUID"); +CREATE index prims_parentid on prims("ParentID"); + +CREATE index primitems_primid on primitems("primID"); + +COMMIT; + + +:VERSION 7 + +BEGIN TRANSACTION; + +ALTER TABLE prims ADD "ColorR" int not null default 0; +ALTER TABLE prims ADD "ColorG" int not null default 0; +ALTER TABLE prims ADD "ColorB" int not null default 0; +ALTER TABLE prims ADD "ColorA" int not null default 0; +ALTER TABLE prims ADD "ParticleSystem" bytea; +ALTER TABLE prims ADD "ClickAction" smallint NOT NULL default 0; + +COMMIT; + + +:VERSION 8 + +BEGIN TRANSACTION; + +ALTER TABLE land ADD "OtherCleanTime" integer NOT NULL default 0; +ALTER TABLE land ADD "Dwell" integer NOT NULL default 0; + +COMMIT; + +:VERSION 9 + +BEGIN TRANSACTION; + +ALTER TABLE prims ADD "Material" smallint NOT NULL default 3; + +COMMIT; + + +:VERSION 10 + +BEGIN TRANSACTION; + +ALTER TABLE regionsettings ADD "sunvectorx" double precision NOT NULL default 0; +ALTER TABLE regionsettings ADD "sunvectory" double precision NOT NULL default 0; +ALTER TABLE regionsettings ADD "sunvectorz" double precision NOT NULL default 0; + +COMMIT; + + +:VERSION 11 + +BEGIN TRANSACTION; + +ALTER TABLE prims ADD "CollisionSound" char(36) not null default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE prims ADD "CollisionSoundVolume" double precision not null default 0.0; + +COMMIT; + + +:VERSION 12 + +BEGIN TRANSACTION; + +ALTER TABLE prims ADD "LinkNumber" integer not null default 0; + +COMMIT; + + +:VERSION 13 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_prims + ( + "UUID" uuid NOT NULL, + "RegionUUID" uuid NULL, + "ParentID" int NULL, + "CreationDate" int NULL, + "Name" varchar(255) NULL, + "SceneGroupID" uuid NULL, + "Text" varchar(255) NULL, + "Description" varchar(255) NULL, + "SitName" varchar(255) NULL, + "TouchName" varchar(255) NULL, + "ObjectFlags" int NULL, + "CreatorID" uuid NULL, + "OwnerID" uuid NULL, + "GroupID" uuid NULL, + "LastOwnerID" uuid NULL, + "OwnerMask" int NULL, + "NextOwnerMask" int NULL, + "GroupMask" int NULL, + "EveryoneMask" int NULL, + "BaseMask" int NULL, + "PositionX" double precision NULL, + "PositionY" double precision NULL, + "PositionZ" double precision NULL, + "GroupPositionX" double precision NULL, + "GroupPositionY" double precision NULL, + "GroupPositionZ" double precision NULL, + "VelocityX" double precision NULL, + "VelocityY" double precision NULL, + "VelocityZ" double precision NULL, + "AngularVelocityX" double precision NULL, + "AngularVelocityY" double precision NULL, + "AngularVelocityZ" double precision NULL, + "AccelerationX" double precision NULL, + "AccelerationY" double precision NULL, + "AccelerationZ" double precision NULL, + "RotationX" double precision NULL, + "RotationY" double precision NULL, + "RotationZ" double precision NULL, + "RotationW" double precision NULL, + "SitTargetOffsetX" double precision NULL, + "SitTargetOffsetY" double precision NULL, + "SitTargetOffsetZ" double precision NULL, + "SitTargetOrientW" double precision NULL, + "SitTargetOrientX" double precision NULL, + "SitTargetOrientY" double precision NULL, + "SitTargetOrientZ" double precision NULL, + "PayPrice" int NOT NULL DEFAULT ((0)), + "PayButton1" int NOT NULL DEFAULT ((0)), + "PayButton2" int NOT NULL DEFAULT ((0)), + "PayButton3" int NOT NULL DEFAULT ((0)), + "PayButton4" int NOT NULL DEFAULT ((0)), + "LoopedSound" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + "LoopedSoundGain" double precision NOT NULL DEFAULT ((0.0)), + "TextureAnimation" bytea NULL, + "OmegaX" double precision NOT NULL DEFAULT ((0.0)), + "OmegaY" double precision NOT NULL DEFAULT ((0.0)), + "OmegaZ" double precision NOT NULL DEFAULT ((0.0)), + "CameraEyeOffsetX" double precision NOT NULL DEFAULT ((0.0)), + "CameraEyeOffsetY" double precision NOT NULL DEFAULT ((0.0)), + "CameraEyeOffsetZ" double precision NOT NULL DEFAULT ((0.0)), + "CameraAtOffsetX" double precision NOT NULL DEFAULT ((0.0)), + "CameraAtOffsetY" double precision NOT NULL DEFAULT ((0.0)), + "CameraAtOffsetZ" double precision NOT NULL DEFAULT ((0.0)), + "ForceMouselook" smallint NOT NULL DEFAULT ((0)), + "ScriptAccessPin" int NOT NULL DEFAULT ((0)), + "AllowedDrop" smallint NOT NULL DEFAULT ((0)), + "DieAtEdge" smallint NOT NULL DEFAULT ((0)), + "SalePrice" int NOT NULL DEFAULT ((10)), + "SaleType" smallint NOT NULL DEFAULT ((0)), + "ColorR" int NOT NULL DEFAULT ((0)), + "ColorG" int NOT NULL DEFAULT ((0)), + "ColorB" int NOT NULL DEFAULT ((0)), + "ColorA" int NOT NULL DEFAULT ((0)), + "ParticleSystem" bytea NULL, + "ClickAction" smallint NOT NULL DEFAULT ((0)), + "Material" smallint NOT NULL DEFAULT ((3)), + "CollisionSound" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + "CollisionSoundVolume" double precision NOT NULL DEFAULT ((0.0)), + "LinkNumber" int NOT NULL DEFAULT ((0)) + ); + +INSERT INTO Tmp_prims ("UUID", "RegionUUID", "ParentID", "CreationDate", "Name", "SceneGroupID", "Text", "Description", "SitName", "TouchName", "ObjectFlags", "CreatorID", "OwnerID", "GroupID", "LastOwnerID", "OwnerMask", "NextOwnerMask", "GroupMask", "EveryoneMask", "BaseMask", "PositionX", "PositionY", "PositionZ", "GroupPositionX", "GroupPositionY", "GroupPositionZ", "VelocityX", "VelocityY", "VelocityZ", "AngularVelocityX", "AngularVelocityY", "AngularVelocityZ", "AccelerationX", "AccelerationY", "AccelerationZ", "RotationX", "RotationY", "RotationZ", "RotationW", "SitTargetOffsetX", "SitTargetOffsetY", "SitTargetOffsetZ", "SitTargetOrientW", "SitTargetOrientX", "SitTargetOrientY", "SitTargetOrientZ", "PayPrice", "PayButton1", "PayButton2", "PayButton3", "PayButton4", "LoopedSound", "LoopedSoundGain", "TextureAnimation", "OmegaX", "OmegaY", "OmegaZ", "CameraEyeOffsetX", "CameraEyeOffsetY", "CameraEyeOffsetZ", "CameraAtOffsetX", "CameraAtOffsetY", "CameraAtOffsetZ", "ForceMouselook", "ScriptAccessPin", "AllowedDrop", "DieAtEdge", "SalePrice", "SaleType", "ColorR", "ColorG", "ColorB", "ColorA", "ParticleSystem", "ClickAction", "Material", "CollisionSound", "CollisionSoundVolume", "LinkNumber") + SELECT cast("UUID" as uuid), cast("RegionUUID" as uuid), "ParentID", "CreationDate", "Name", cast("SceneGroupID" as uuid), "Text", "Description", "SitName", "TouchName", "ObjectFlags", cast("CreatorID" as uuid), cast("OwnerID" as uuid), cast("GroupID" as uuid), cast("LastOwnerID" as uuid), "OwnerMask", "NextOwnerMask", "GroupMask", "EveryoneMask", "BaseMask", "PositionX", "PositionY", "PositionZ", "GroupPositionX", "GroupPositionY", "GroupPositionZ", "VelocityX", "VelocityY", "VelocityZ", "AngularVelocityX", "AngularVelocityY", "AngularVelocityZ", "AccelerationX", "AccelerationY", "AccelerationZ", "RotationX", "RotationY", "RotationZ", "RotationW", "SitTargetOffsetX", "SitTargetOffsetY", "SitTargetOffsetZ", "SitTargetOrientW", "SitTargetOrientX", "SitTargetOrientY", "SitTargetOrientZ", "PayPrice", "PayButton1", "PayButton2", "PayButton3", "PayButton4", cast("LoopedSound" as uuid), "LoopedSoundGain", "TextureAnimation", "OmegaX", "OmegaY", "OmegaZ", "CameraEyeOffsetX", "CameraEyeOffsetY", "CameraEyeOffsetZ", "CameraAtOffsetX", "CameraAtOffsetY", "CameraAtOffsetZ", "ForceMouselook", "ScriptAccessPin", "AllowedDrop", "DieAtEdge", "SalePrice", "SaleType", "ColorR", "ColorG", "ColorB", "ColorA", "ParticleSystem", "ClickAction", "Material", cast("CollisionSound" as uuid), "CollisionSoundVolume", "LinkNumber" + FROM prims ; + +DROP TABLE prims; + +alter table Tmp_prims rename to prims; + +ALTER TABLE prims ADD CONSTRAINT + PK__prims__10566F31 PRIMARY KEY + ( + "UUID" + ); + + +CREATE INDEX prims_regionuuid ON prims + ( + "RegionUUID" + ); + +CREATE INDEX prims_parentid ON prims + ( + "ParentID" + ); + +COMMIT; + + +:VERSION 14 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_primshapes + ( + "UUID" uuid NOT NULL, + "Shape" int NULL, + "ScaleX" double precision NULL, + "ScaleY" double precision NULL, + "ScaleZ" double precision NULL, + "PCode" int NULL, + "PathBegin" int NULL, + "PathEnd" int NULL, + "PathScaleX" int NULL, + "PathScaleY" int NULL, + "PathShearX" int NULL, + "PathShearY" int NULL, + "PathSkew" int NULL, + "PathCurve" int NULL, + "PathRadiusOffset" int NULL, + "PathRevolutions" int NULL, + "PathTaperX" int NULL, + "PathTaperY" int NULL, + "PathTwist" int NULL, + "PathTwistBegin" int NULL, + "ProfileBegin" int NULL, + "ProfileEnd" int NULL, + "ProfileCurve" int NULL, + "ProfileHollow" int NULL, + "State" int NULL, + "Texture" bytea NULL, + "ExtraParams" bytea NULL + ); + +INSERT INTO Tmp_primshapes ("UUID", "Shape", "ScaleX", "ScaleY", "ScaleZ", "PCode", "PathBegin", "PathEnd", "PathScaleX", "PathScaleY", "PathShearX", "PathShearY", "PathSkew", "PathCurve", "PathRadiusOffset", "PathRevolutions", "PathTaperX", "PathTaperY", "PathTwist", "PathTwistBegin", "ProfileBegin", "ProfileEnd", "ProfileCurve", "ProfileHollow", "State", "Texture", "ExtraParams") + SELECT cast("UUID" as uuid), "Shape", "ScaleX", "ScaleY", "ScaleZ", "PCode", "PathBegin", "PathEnd", "PathScaleX", "PathScaleY", "PathShearX", "PathShearY", "PathSkew", "PathCurve", "PathRadiusOffset", "PathRevolutions", "PathTaperX", "PathTaperY", "PathTwist", "PathTwistBegin", "ProfileBegin", "ProfileEnd", "ProfileCurve", "ProfileHollow", "State", "Texture", "ExtraParams" + FROM primshapes; + +DROP TABLE primshapes; + +alter table Tmp_primshapes rename to primshapes; + +ALTER TABLE primshapes ADD CONSTRAINT + PK__primshapes__0880433F PRIMARY KEY + ( + "UUID" + ); + +COMMIT; + + +:VERSION 15 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_primitems + ( + "itemID" uuid NOT NULL, + "primID" uuid NULL, + "assetID" uuid NULL, + "parentFolderID" uuid NULL, + "invType" int NULL, + "assetType" int NULL, + "name" varchar(255) NULL, + "description" varchar(255) NULL, + "creationDate" varchar(255) NULL, + "creatorID" uuid NULL, + "ownerID" uuid NULL, + "lastOwnerID" uuid NULL, + "groupID" uuid NULL, + "nextPermissions" int NULL, + "currentPermissions" int NULL, + "basePermissions" int NULL, + "everyonePermissions" int NULL, + "groupPermissions" int NULL, + flags int NOT NULL DEFAULT ((0)) + ); + +INSERT INTO Tmp_primitems ("itemID", "primID", "assetID", "parentFolderID", "invType", "assetType", "name", "description", "creationDate", "creatorID", "ownerID", "lastOwnerID", "groupID", "nextPermissions", "currentPermissions", "basePermissions", "everyonePermissions", "groupPermissions", flags) + SELECT cast("itemID" as uuid), cast("primID" as uuid), cast("assetID" as uuid), cast("parentFolderID" as uuid), "invType", "assetType", "name", "description", "creationDate", cast("creatorID" as uuid), cast("ownerID" as uuid), cast("lastOwnerID" as uuid), cast("groupID" as uuid), "nextPermissions", "currentPermissions", "basePermissions", "everyonePermissions", "groupPermissions", flags + FROM primitems ; + +DROP TABLE primitems; + +alter table Tmp_primitems rename to primitems; + +ALTER TABLE primitems ADD CONSTRAINT + PK__primitems__0A688BB1 PRIMARY KEY + ( + "itemID" + ); + +CREATE INDEX primitems_primid ON primitems + ( + "primID" + ) ; + +COMMIT; + + +:VERSION 16 + + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_terrain + ( + "RegionUUID" uuid NULL, + "Revision" int NULL, + "Heightfield" bytea NULL + ); + +INSERT INTO Tmp_terrain ("RegionUUID", "Revision", "Heightfield") + SELECT cast("RegionUUID" as uuid), "Revision", "Heightfield" + FROM terrain ; + +DROP TABLE terrain; + +alter table Tmp_terrain rename to terrain; + +COMMIT; + + +:VERSION 17 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_land + ( + "UUID" uuid NOT NULL, + "RegionUUID" uuid NULL, + "LocalLandID" int NULL, + "Bitmap" bytea NULL, + "Name" varchar(255) NULL, + "Description" varchar(255) NULL, + "OwnerUUID" uuid NULL, + "IsGroupOwned" boolean NULL, + "Area" int NULL, + "AuctionID" int NULL, + "Category" int NULL, + "ClaimDate" int NULL, + "ClaimPrice" int NULL, + "GroupUUID" uuid NULL, + "SalePrice" int NULL, + "LandStatus" int NULL, + "LandFlags" int NULL, + "LandingType" int NULL, + "MediaAutoScale" int NULL, + "MediaTextureUUID" uuid NULL, + "MediaURL" varchar(255) NULL, + "MusicURL" varchar(255) NULL, + "PassHours" double precision NULL, + "PassPrice" int NULL, + "SnapshotUUID" uuid NULL, + "UserLocationX" double precision NULL, + "UserLocationY" double precision NULL, + "UserLocationZ" double precision NULL, + "UserLookAtX" double precision NULL, + "UserLookAtY" double precision NULL, + "UserLookAtZ" double precision NULL, + "AuthbuyerID" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + "OtherCleanTime" int NOT NULL DEFAULT ((0)), + "Dwell" int NOT NULL DEFAULT ((0)) + ); + +INSERT INTO Tmp_land ("UUID", "RegionUUID", "LocalLandID", "Bitmap", "Name", "Description", "OwnerUUID", "IsGroupOwned", "Area", "AuctionID", "Category", "ClaimDate", "ClaimPrice", "GroupUUID", "SalePrice", "LandStatus", "LandFlags", "LandingType", "MediaAutoScale", "MediaTextureUUID", "MediaURL", "MusicURL", "PassHours", "PassPrice", "SnapshotUUID", "UserLocationX", "UserLocationY", "UserLocationZ", "UserLookAtX", "UserLookAtY", "UserLookAtZ", "AuthbuyerID", "OtherCleanTime", "Dwell") + SELECT cast("UUID" as uuid), cast("RegionUUID" as uuid), "LocalLandID", "Bitmap", "Name", "Description", cast("OwnerUUID" as uuid), "IsGroupOwned", "Area", "AuctionID", "Category", "ClaimDate", "ClaimPrice", cast("GroupUUID" as uuid), "SalePrice", "LandStatus", "LandFlags", "LandingType", "MediaAutoScale", cast("MediaTextureUUID" as uuid), "MediaURL", "MusicURL", "PassHours", "PassPrice", cast("SnapshotUUID" as uuid), "UserLocationX", "UserLocationY", "UserLocationZ", "UserLookAtX", "UserLookAtY", "UserLookAtZ", cast("AuthbuyerID" as uuid), "OtherCleanTime", "Dwell" + FROM land ; + +DROP TABLE land; + +alter table Tmp_land rename to land; + +ALTER TABLE land ADD CONSTRAINT + PK__land__65A475E71BFD2C07 PRIMARY KEY + ( + "UUID" + ); + +Create index on land (lower("Name")); + +COMMIT; + + + +:VERSION 18 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_landaccesslist + ( + "LandUUID" uuid NULL, + "AccessUUID" uuid NULL, + "Flags" int NULL + ); + +INSERT INTO Tmp_landaccesslist ("LandUUID", "AccessUUID", "Flags") + SELECT cast("LandUUID" as uuid), cast("AccessUUID" as uuid), "Flags" + FROM landaccesslist ; + +DROP TABLE landaccesslist; + +alter table Tmp_landaccesslist rename to landaccesslist; + +COMMIT; + + + +:VERSION 19 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_regionban + ( + "regionUUID" uuid NOT NULL, + "bannedUUID" uuid NOT NULL, + "bannedIp" varchar(16) NOT NULL, + "bannedIpHostMask" varchar(16) NOT NULL + ); + +INSERT INTO Tmp_regionban ("regionUUID", "bannedUUID", "bannedIp", "bannedIpHostMask") + SELECT cast("regionUUID" as uuid), cast("bannedUUID" as uuid), "bannedIp", "bannedIpHostMask" + FROM regionban ; + +DROP TABLE regionban; + +alter table Tmp_regionban rename to regionban; + +COMMIT; + + +:VERSION 20 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_regionsettings + ( + "regionUUID" uuid NOT NULL, + "block_terraform" boolean NOT NULL, + "block_fly" boolean NOT NULL, + "allow_damage" boolean NOT NULL, + "restrict_pushing" boolean NOT NULL, + "allow_land_resell" boolean NOT NULL, + "allow_land_join_divide" boolean NOT NULL, + "block_show_in_search" boolean NOT NULL, + "agent_limit" int NOT NULL, + "object_bonus" double precision NOT NULL, + "maturity" int NOT NULL, + "disable_scripts" boolean NOT NULL, + "disable_collisions" boolean NOT NULL, + "disable_physics" boolean NOT NULL, + "terrain_texture_1" uuid NOT NULL, + "terrain_texture_2" uuid NOT NULL, + "terrain_texture_3" uuid NOT NULL, + "terrain_texture_4" uuid NOT NULL, + "elevation_1_nw" double precision NOT NULL, + "elevation_2_nw" double precision NOT NULL, + "elevation_1_ne" double precision NOT NULL, + "elevation_2_ne" double precision NOT NULL, + "elevation_1_se" double precision NOT NULL, + "elevation_2_se" double precision NOT NULL, + "elevation_1_sw" double precision NOT NULL, + "elevation_2_sw" double precision NOT NULL, + "water_height" double precision NOT NULL, + "terrain_raise_limit" double precision NOT NULL, + "terrain_lower_limit" double precision NOT NULL, + "use_estate_sun" boolean NOT NULL, + "fixed_sun" boolean NOT NULL, + "sun_position" double precision NOT NULL, + "covenant" uuid NULL DEFAULT (NULL), + "Sandbox" boolean NOT NULL, + "sunvectorx" double precision NOT NULL DEFAULT ((0)), + "sunvectory" double precision NOT NULL DEFAULT ((0)), + "sunvectorz" double precision NOT NULL DEFAULT ((0)) + ); + +INSERT INTO Tmp_regionsettings ("regionUUID", "block_terraform", "block_fly", "allow_damage", "restrict_pushing", "allow_land_resell", "allow_land_join_divide", "block_show_in_search", "agent_limit", "object_bonus", "maturity", "disable_scripts", "disable_collisions", "disable_physics", "terrain_texture_1", "terrain_texture_2", "terrain_texture_3", "terrain_texture_4", "elevation_1_nw", "elevation_2_nw", "elevation_1_ne", "elevation_2_ne", "elevation_1_se", "elevation_2_se", "elevation_1_sw", "elevation_2_sw", "water_height", "terrain_raise_limit", "terrain_lower_limit", "use_estate_sun", "fixed_sun", "sun_position", "covenant", "Sandbox", "sunvectorx", "sunvectory", "sunvectorz") + SELECT cast("regionUUID" as uuid), "block_terraform", "block_fly", "allow_damage", "restrict_pushing", "allow_land_resell", "allow_land_join_divide", "block_show_in_search", "agent_limit", "object_bonus", "maturity", "disable_scripts", "disable_collisions", "disable_physics", cast("terrain_texture_1" as uuid), cast("terrain_texture_2" as uuid), cast("terrain_texture_3" as uuid), cast("terrain_texture_4" as uuid), "elevation_1_nw", "elevation_2_nw", "elevation_1_ne", "elevation_2_ne", "elevation_1_se", "elevation_2_se", "elevation_1_sw", "elevation_2_sw", "water_height", "terrain_raise_limit", "terrain_lower_limit", "use_estate_sun", "fixed_sun", "sun_position", cast("covenant" as uuid), "Sandbox", "sunvectorx", "sunvectory", "sunvectorz" + FROM regionsettings ; + +DROP TABLE regionsettings; + +alter table Tmp_regionsettings rename to regionsettings; + +ALTER TABLE regionsettings ADD CONSTRAINT + PK__regionse__5B35159D21B6055D PRIMARY KEY + ( + "regionUUID" + ); + +COMMIT; + + +:VERSION 21 + +BEGIN TRANSACTION; + +ALTER TABLE prims ADD "PassTouches" boolean not null default false; + +COMMIT; + + +:VERSION 22 + +BEGIN TRANSACTION; + +ALTER TABLE regionsettings ADD "loaded_creation_date" varchar(20) ; +ALTER TABLE regionsettings ADD "loaded_creation_time" varchar(20) ; +ALTER TABLE regionsettings ADD "loaded_creation_id" varchar(64) ; + +COMMIT; + +:VERSION 23 + +BEGIN TRANSACTION; + +ALTER TABLE regionsettings DROP COLUMN "loaded_creation_date"; +ALTER TABLE regionsettings DROP COLUMN "loaded_creation_time"; +ALTER TABLE regionsettings ADD "loaded_creation_datetime" int NOT NULL default 0; + +COMMIT; + +:VERSION 24 + +BEGIN TRANSACTION; + +ALTER TABLE prims ADD "MediaURL" varchar(255); +ALTER TABLE primshapes ADD "Media" TEXT NULL; + +COMMIT; + +:VERSION 25 + +BEGIN TRANSACTION; +CREATE TABLE regionwindlight ( + "region_id" varchar(36) NOT NULL DEFAULT '000000-0000-0000-0000-000000000000' PRIMARY KEY, + "water_color_r" double precision NOT NULL DEFAULT '4.000000', + water_color_g double precision NOT NULL DEFAULT '38.000000', + water_color_b double precision NOT NULL DEFAULT '64.000000', + water_fog_density_exponent double precision NOT NULL DEFAULT '4.0', + underwater_fog_modifier double precision NOT NULL DEFAULT '0.25', + reflection_wavelet_scale_1 double precision NOT NULL DEFAULT '2.0', + reflection_wavelet_scale_2 double precision NOT NULL DEFAULT '2.0', + reflection_wavelet_scale_3 double precision NOT NULL DEFAULT '2.0', + fresnel_scale double precision NOT NULL DEFAULT '0.40', + fresnel_offset double precision NOT NULL DEFAULT '0.50', + refract_scale_above double precision NOT NULL DEFAULT '0.03', + refract_scale_below double precision NOT NULL DEFAULT '0.20', + blur_multiplier double precision NOT NULL DEFAULT '0.040', + big_wave_direction_x double precision NOT NULL DEFAULT '1.05', + big_wave_direction_y double precision NOT NULL DEFAULT '-0.42', + little_wave_direction_x double precision NOT NULL DEFAULT '1.11', + little_wave_direction_y double precision NOT NULL DEFAULT '-1.16', + normal_map_texture varchar(36) NOT NULL DEFAULT '822ded49-9a6c-f61c-cb89-6df54f42cdf4', + horizon_r double precision NOT NULL DEFAULT '0.25', + horizon_g double precision NOT NULL DEFAULT '0.25', + horizon_b double precision NOT NULL DEFAULT '0.32', + horizon_i double precision NOT NULL DEFAULT '0.32', + haze_horizon double precision NOT NULL DEFAULT '0.19', + blue_density_r double precision NOT NULL DEFAULT '0.12', + blue_density_g double precision NOT NULL DEFAULT '0.22', + blue_density_b double precision NOT NULL DEFAULT '0.38', + blue_density_i double precision NOT NULL DEFAULT '0.38', + haze_density double precision NOT NULL DEFAULT '0.70', + density_multiplier double precision NOT NULL DEFAULT '0.18', + distance_multiplier double precision NOT NULL DEFAULT '0.8', + max_altitude int NOT NULL DEFAULT '1605', + sun_moon_color_r double precision NOT NULL DEFAULT '0.24', + sun_moon_color_g double precision NOT NULL DEFAULT '0.26', + sun_moon_color_b double precision NOT NULL DEFAULT '0.30', + sun_moon_color_i double precision NOT NULL DEFAULT '0.30', + sun_moon_position double precision NOT NULL DEFAULT '0.317', + ambient_r double precision NOT NULL DEFAULT '0.35', + ambient_g double precision NOT NULL DEFAULT '0.35', + ambient_b double precision NOT NULL DEFAULT '0.35', + ambient_i double precision NOT NULL DEFAULT '0.35', + east_angle double precision NOT NULL DEFAULT '0.00', + sun_glow_focus double precision NOT NULL DEFAULT '0.10', + sun_glow_size double precision NOT NULL DEFAULT '1.75', + scene_gamma double precision NOT NULL DEFAULT '1.00', + star_brightness double precision NOT NULL DEFAULT '0.00', + cloud_color_r double precision NOT NULL DEFAULT '0.41', + cloud_color_g double precision NOT NULL DEFAULT '0.41', + cloud_color_b double precision NOT NULL DEFAULT '0.41', + cloud_color_i double precision NOT NULL DEFAULT '0.41', + cloud_x double precision NOT NULL DEFAULT '1.00', + cloud_y double precision NOT NULL DEFAULT '0.53', + cloud_density double precision NOT NULL DEFAULT '1.00', + cloud_coverage double precision NOT NULL DEFAULT '0.27', + cloud_scale double precision NOT NULL DEFAULT '0.42', + cloud_detail_x double precision NOT NULL DEFAULT '1.00', + cloud_detail_y double precision NOT NULL DEFAULT '0.53', + cloud_detail_density double precision NOT NULL DEFAULT '0.12', + cloud_scroll_x double precision NOT NULL DEFAULT '0.20', + cloud_scroll_x_lock smallint NOT NULL DEFAULT '0', + cloud_scroll_y double precision NOT NULL DEFAULT '0.01', + cloud_scroll_y_lock smallint NOT NULL DEFAULT '0', + draw_classic_clouds smallint NOT NULL DEFAULT '1' +); + +COMMIT; + +:VERSION 26 + +BEGIN TRANSACTION; + +ALTER TABLE regionsettings ADD "map_tile_ID" CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; + +COMMIT; + +:VERSION 27 #--------------------- + +BEGIN TRANSACTION; +ALTER TABLE land ADD "MediaType" VARCHAR(32) NOT NULL DEFAULT 'none/none' ; +ALTER TABLE land ADD "MediaDescription" VARCHAR(255) NOT NULL DEFAULT ''; +ALTER TABLE land ADD "MediaSize" VARCHAR(16) NOT NULL DEFAULT '0,0'; +ALTER TABLE land ADD "MediaLoop" boolean NOT NULL DEFAULT false; +ALTER TABLE land ADD "ObscureMusic" boolean NOT NULL DEFAULT false; +ALTER TABLE land ADD "ObscureMedia" boolean NOT NULL DEFAULT false; +COMMIT; + +:VERSION 28 #--------------------- + +BEGIN TRANSACTION; + +ALTER TABLE prims +alter column "CreatorID" set DEFAULT '00000000-0000-0000-0000-000000000000' ; + +ALTER TABLE prims ALTER COLUMN "CreatorID" set NOT NULL; + +ALTER TABLE primitems +alter column "creatorID" set DEFAULT '00000000-0000-0000-0000-000000000000' ; + +ALTER TABLE primitems ALTER COLUMN "creatorID" set NOT NULL; + +COMMIT; + +:VERSION 29 #----------------- Region Covenant changed time + +BEGIN TRANSACTION; + +ALTER TABLE regionsettings ADD "covenant_datetime" int NOT NULL default 0; + +COMMIT; + +:VERSION 30 #------------------Migrate "creatorID" storage to varchars instead of UUIDs for HG support + +BEGIN TRANSACTION; + +alter table prims rename column "CreatorID" to "CreatorIDOld"; +alter table primitems rename column "creatorID" to "creatorIDOld"; + +COMMIT; + +:VERSION 31 #--------------------- + +BEGIN TRANSACTION; + +ALTER TABLE prims ADD "CreatorID" varchar(255); +ALTER TABLE primitems ADD "creatorID" varchar(255); + +COMMIT; + +:VERSION 32 #--------------------- + +BEGIN TRANSACTION; + +UPDATE prims SET "CreatorID" = cast("CreatorIDOld" as varchar(255)); +UPDATE primitems SET "creatorID" = cast("creatorIDOld" as varchar(255)); + +COMMIT; + +:VERSION 33 #--------------------- + +BEGIN TRANSACTION; + +ALTER TABLE prims alter column "CreatorID" set default '00000000-0000-0000-0000-000000000000' ; + +ALTER TABLE prims ALTER COLUMN "CreatorID" set NOT NULL; + +ALTER TABLE primitems alter column "creatorID" set DEFAULT '00000000-0000-0000-0000-000000000000' ; + +ALTER TABLE primitems ALTER COLUMN "creatorID" set NOT NULL; + +COMMIT; + +:VERSION 34 #--------------- Telehub support + +BEGIN TRANSACTION; + +CREATE TABLE spawn_points( + "RegionUUID" uuid NOT NULL PRIMARY KEY, + "Yaw" double precision NOT NULL, + "Pitch" double precision NOT NULL, + "Distance" double precision NOT NULL +); + +ALTER TABLE regionsettings ADD "TelehubObject" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; + +COMMIT; + +:VERSION 35 #---------------- Parcels for sale + +BEGIN TRANSACTION; + +ALTER TABLE regionsettings ADD "parcel_tile_ID" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; + +COMMIT; + +:VERSION 36 #---------------- Timed bans/access + +BEGIN TRANSACTION; + +ALTER TABLE landaccesslist ADD "Expires" integer NOT NULL DEFAULT 0; + +COMMIT; + +:VERSION 37 #---------------- Environment Settings + +BEGIN TRANSACTION; + +CREATE TABLE regionenvironment( + "region_id" uuid NOT NULL primary key, + "llsd_settings" varchar NOT NULL +); + +COMMIT; + +:VERSION 38 #---------------- Dynamic attributes + +BEGIN TRANSACTION; + +ALTER TABLE prims ADD "DynAttrs" TEXT; + +COMMIT; + +:VERSION 39 #---------------- Extra physics params + +BEGIN TRANSACTION; + +ALTER TABLE prims ADD "PhysicsShapeType" smallint NOT NULL default '0'; +ALTER TABLE prims ADD "Density" double precision NOT NULL default '1000'; +ALTER TABLE prims ADD "GravityModifier" double precision NOT NULL default '1'; +ALTER TABLE prims ADD "Friction" double precision NOT NULL default '0.6'; +ALTER TABLE prims ADD "Restitution" double precision NOT NULL default '0.5'; + +COMMIT; diff --git a/OpenSim/Data/PGSQL/Resources/UserAccount.migrations b/OpenSim/Data/PGSQL/Resources/UserAccount.migrations new file mode 100644 index 0000000000..c785463325 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/UserAccount.migrations @@ -0,0 +1,51 @@ +:VERSION 1 + +CREATE TABLE UserAccounts ( + "PrincipalID" uuid NOT NULL Primary key, + "ScopeID" uuid NOT NULL, + "FirstName" varchar(64) NOT NULL, + "LastName" varchar(64) NOT NULL, + "Email" varchar(64) NULL, + "ServiceURLs" text NULL, + "Created" int default NULL +); + + +:VERSION 2 + +BEGIN TRANSACTION; + +INSERT INTO UserAccounts ("PrincipalID", "ScopeID", "FirstName", "LastName", "Email", "ServiceURLs", "Created") +SELECT UUID AS "PrincipalID", '00000000-0000-0000-0000-000000000000' AS "ScopeID", +username AS "FirstName", +lastname AS "LastName", +email as "Email", ( +'AssetServerURI=' + +userAssetURI + ' InventoryServerURI=' + userInventoryURI + ' GatewayURI= HomeURI=') AS "ServiceURLs", +created as "Created" FROM users; + +COMMIT; + +:VERSION 3 + +BEGIN TRANSACTION; + +CREATE UNIQUE INDEX "PrincipalID" ON UserAccounts("PrincipalID"); +CREATE INDEX "Email" ON UserAccounts("Email"); +CREATE INDEX "FirstName" ON UserAccounts("FirstName"); +CREATE INDEX "LastName" ON UserAccounts("LastName"); +CREATE INDEX Name ON UserAccounts("FirstName","LastName"); + +COMMIT; + +:VERSION 4 + +BEGIN TRANSACTION; + +ALTER TABLE UserAccounts ADD "UserLevel" integer NOT NULL DEFAULT 0; +ALTER TABLE UserAccounts ADD "UserFlags" integer NOT NULL DEFAULT 0; +ALTER TABLE UserAccounts ADD "UserTitle" varchar(64) NOT NULL DEFAULT ''; + +COMMIT; + + diff --git a/OpenSim/Data/PGSQL/Resources/UserProfiles.migrations b/OpenSim/Data/PGSQL/Resources/UserProfiles.migrations new file mode 100644 index 0000000000..f23c87087c --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/UserProfiles.migrations @@ -0,0 +1,83 @@ +:VERSION 1 # ------------------------------- + +begin; + +CREATE TABLE classifieds ( + "classifieduuid" char(36) NOT NULL, + "creatoruuid" char(36) NOT NULL, + "creationdate" integer NOT NULL, + "expirationdate" integer NOT NULL, + "category" varchar(20) NOT NULL, + "name" varchar(255) NOT NULL, + "description" text NOT NULL, + "parceluuid" char(36) NOT NULL, + "parentestate" integer NOT NULL, + "snapshotuuid" char(36) NOT NULL, + "simname" varchar(255) NOT NULL, + "posglobal" varchar(255) NOT NULL, + "parcelname" varchar(255) NOT NULL, + "classifiedflags" integer NOT NULL, + "priceforlisting" integer NOT NULL, + constraint classifiedspk PRIMARY KEY ("classifieduuid") +); + + +CREATE TABLE usernotes ( + "useruuid" varchar(36) NOT NULL, + "targetuuid" varchar(36) NOT NULL, + "notes" text NOT NULL, + constraint usernoteuk UNIQUE ("useruuid","targetuuid") +); + + +CREATE TABLE userpicks ( + "pickuuid" varchar(36) NOT NULL, + "creatoruuid" varchar(36) NOT NULL, + "toppick" boolean NOT NULL, + "parceluuid" varchar(36) NOT NULL, + "name" varchar(255) NOT NULL, + "description" text NOT NULL, + "snapshotuuid" varchar(36) NOT NULL, + "user" varchar(255) NOT NULL, + "originalname" varchar(255) NOT NULL, + "simname" varchar(255) NOT NULL, + "posglobal" varchar(255) NOT NULL, + "sortorder" integer NOT NULL, + "enabled" boolean NOT NULL, + PRIMARY KEY ("pickuuid") +); + + +CREATE TABLE userprofile ( + "useruuid" varchar(36) NOT NULL, + "profilePartner" varchar(36) NOT NULL, + "profileAllowPublish" bytea NOT NULL, + "profileMaturePublish" bytea NOT NULL, + "profileURL" varchar(255) NOT NULL, + "profileWantToMask" integer NOT NULL, + "profileWantToText" text NOT NULL, + "profileSkillsMask" integer NOT NULL, + "profileSkillsText" text NOT NULL, + "profileLanguages" text NOT NULL, + "profileImage" varchar(36) NOT NULL, + "profileAboutText" text NOT NULL, + "profileFirstImage" varchar(36) NOT NULL, + "profileFirstText" text NOT NULL, + PRIMARY KEY ("useruuid") +); + +commit; + +:VERSION 2 # ------------------------------- + +begin; +CREATE TABLE userdata ( + "UserId" char(36) NOT NULL, + "TagId" varchar(64) NOT NULL, + "DataKey" varchar(255), + "DataVal" varchar(255), + PRIMARY KEY ("UserId","TagId") +); + +commit; + diff --git a/OpenSim/Data/PGSQL/Resources/UserStore.migrations b/OpenSim/Data/PGSQL/Resources/UserStore.migrations new file mode 100644 index 0000000000..974d48995b --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/UserStore.migrations @@ -0,0 +1,404 @@ +:VERSION 1 + +CREATE TABLE users ( + "UUID" varchar(36) NOT NULL default '' Primary Key, + "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" double precision default NULL, + "homeLocationY" double precision default NULL, + "homeLocationZ" double precision default NULL, + "homeLookAtX" double precision default NULL, + "homeLookAtY" double precision default NULL, + "homeLookAtZ" double precision 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" text, + "profileFirstText" text, + "profileImage" varchar(36) default NULL, + "profileFirstImage" varchar(36) default NULL, + "webLoginKey" varchar(36) default NULL +); + +CREATE INDEX "usernames" ON users +( + "username" ASC, + "lastname" ASC +); + + +CREATE TABLE agents ( + "UUID" varchar(36) NOT NULL Primary Key, + "sessionID" varchar(36) NOT NULL, + "secureSessionID" varchar(36) NOT NULL, + "agentIP" varchar(16) NOT NULL, + "agentPort" int NOT NULL, + "agentOnline" smallint NOT NULL, + "loginTime" int NOT NULL, + "logoutTime" int NOT NULL, + "currentRegion" varchar(36) NOT NULL, + "currentHandle" bigint NOT NULL, + "currentPos" varchar(64) NOT NULL +); + +CREATE INDEX session ON agents +( + "sessionID" ASC +); + +CREATE INDEX ssession ON agents +( + "secureSessionID" ASC +); + + +CREATE TABLE userfriends( + "ownerID" varchar(50) NOT NULL, + "friendID" varchar(50) NOT NULL, + "friendPerms" varchar(50) NOT NULL, + "datetimestamp" varchar(50) NOT NULL +); + +CREATE TABLE avatarappearance ( + "Owner" varchar(36) NOT NULL primary key, + "Serial" int NOT NULL, + "Visual_Params" bytea NOT NULL, + "Texture" bytea NOT NULL, + "Avatar_Height" double precision NOT NULL, + "Body_Item" varchar(36) NOT NULL, + "Body_Asset" varchar(36) NOT NULL, + "Skin_Item" varchar(36) NOT NULL, + "Skin_Asset" varchar(36) NOT NULL, + "Hair_Item" varchar(36) NOT NULL, + "Hair_Asset" varchar(36) NOT NULL, + "Eyes_Item" varchar(36) NOT NULL, + "Eyes_Asset" varchar(36) NOT NULL, + "Shirt_Item" varchar(36) NOT NULL, + "Shirt_Asset" varchar(36) NOT NULL, + "Pants_Item" varchar(36) NOT NULL, + "Pants_Asset" varchar(36) NOT NULL, + "Shoes_Item" varchar(36) NOT NULL, + "Shoes_Asset" varchar(36) NOT NULL, + "Socks_Item" varchar(36) NOT NULL, + "Socks_Asset" varchar(36) NOT NULL, + "Jacket_Item" varchar(36) NOT NULL, + "Jacket_Asset" varchar(36) NOT NULL, + "Gloves_Item" varchar(36) NOT NULL, + "Gloves_Asset" varchar(36) NOT NULL, + "Undershirt_Item" varchar(36) NOT NULL, + "Undershirt_Asset" varchar(36) NOT NULL, + "Underpants_Item" varchar(36) NOT NULL, + "Underpants_Asset" varchar(36) NOT NULL, + "Skirt_Item" varchar(36) NOT NULL, + "Skirt_Asset" varchar(36) NOT NULL +); + +:VERSION 2 + +BEGIN TRANSACTION; + +ALTER TABLE users ADD "homeRegionID" varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE users ADD "userFlags" int NOT NULL default 0; +ALTER TABLE users ADD "godLevel" int NOT NULL default 0; +ALTER TABLE users ADD "customType" varchar(32) not null default ''; +ALTER TABLE users ADD "partner" varchar(36) not null default '00000000-0000-0000-0000-000000000000'; + +COMMIT; + + +:VERSION 3 + +BEGIN TRANSACTION; + +CREATE TABLE avatarattachments ( + "UUID" varchar(36) NOT NULL + , "attachpoint" int NOT NULL + , item varchar(36) NOT NULL + , asset varchar(36) NOT NULL); + +CREATE INDEX IX_avatarattachments ON avatarattachments + ( + "UUID" + ); + +COMMIT; + + +:VERSION 4 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_userfriends + ( + "ownerID" varchar(36) NOT NULL, + "friendID" varchar(36) NOT NULL, + "friendPerms" int NOT NULL, + "datetimestamp" int NOT NULL + ); + +INSERT INTO Tmp_userfriends ("ownerID", "friendID", "friendPerms", "datetimestamp") + SELECT cast("ownerID" as varchar(36)), cast("friendID" as varchar(36)), cast("friendPerms" as int), cast("datetimestamp" as int) + FROM userfriends; + +DROP TABLE userfriends; + +alter table Tmp_userfriends rename to userfriends; + +CREATE INDEX IX_userfriends_ownerID ON userfriends + ( + "ownerID" + ); + +CREATE INDEX IX_userfriends_friendID ON userfriends + ( + "friendID" + ); + +COMMIT; + + +:VERSION 5 + +BEGIN TRANSACTION; + + ALTER TABLE users add "email" varchar(250); + +COMMIT; + + +:VERSION 6 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_users + ( + "UUID" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + "username" varchar(32) NOT NULL, + "lastname" varchar(32) NOT NULL, + "passwordHash" varchar(32) NOT NULL, + "passwordSalt" varchar(32) NOT NULL, + "homeRegion" bigint NULL DEFAULT (NULL), + "homeLocationX" double precision NULL DEFAULT (NULL), + "homeLocationY" double precision NULL DEFAULT (NULL), + "homeLocationZ" double precision NULL DEFAULT (NULL), + "homeLookAtX" double precision NULL DEFAULT (NULL), + "homeLookAtY" double precision NULL DEFAULT (NULL), + "homeLookAtZ" double precision NULL DEFAULT (NULL), + "created" int NOT NULL, + "lastLogin" int NOT NULL, + "userInventoryURI" varchar(255) NULL DEFAULT (NULL), + "userAssetURI" varchar(255) NULL DEFAULT (NULL), + "profileCanDoMask" int NULL DEFAULT (NULL), + "profileWantDoMask" int NULL DEFAULT (NULL), + "profileAboutText" text NULL, + "profileFirstText" text NULL, + "profileImage" uuid NULL DEFAULT (NULL), + "profileFirstImage" uuid NULL DEFAULT (NULL), + "webLoginKey" uuid NULL DEFAULT (NULL), + "homeRegionID" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + "userFlags" int NOT NULL DEFAULT ((0)), + "godLevel" int NOT NULL DEFAULT ((0)), + "customType" varchar(32) NOT NULL DEFAULT (''), + "partner" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + email varchar(250) NULL + ); + +INSERT INTO Tmp_users ("UUID", "username", "lastname", "passwordHash", "passwordSalt", "homeRegion", "homeLocationX", "homeLocationY", "homeLocationZ", "homeLookAtX", "homeLookAtY", "homeLookAtZ", "created", "lastLogin", "userInventoryURI", "userAssetURI", "profileCanDoMask", "profileWantDoMask", "profileAboutText", "profileFirstText", "profileImage", "profileFirstImage", "webLoginKey", "homeRegionID", "userFlags", "godLevel", "customType", "partner", email) + SELECT cast("UUID" as uuid), "username", "lastname", "passwordHash", "passwordSalt", "homeRegion", "homeLocationX", "homeLocationY", "homeLocationZ", "homeLookAtX", "homeLookAtY", "homeLookAtZ", "created", "lastLogin", "userInventoryURI", "userAssetURI", "profileCanDoMask", "profileWantDoMask", "profileAboutText", "profileFirstText", cast("profileImage" as uuid), cast("profileFirstImage" as uuid), cast("webLoginKey" as uuid), cast("homeRegionID" as uuid), "userFlags", "godLevel", "customType", cast("partner" as uuid), email + FROM users ; + +DROP TABLE users; + +alter table Tmp_users rename to users; + +ALTER TABLE users ADD CONSTRAINT + PK__users__65A475E737A5467C PRIMARY KEY + ( + "UUID" + ); + +CREATE INDEX "usernames" ON users + ( + "username", + "lastname" + ); + +COMMIT; + + +:VERSION 7 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_agents + ( + "UUID" uuid NOT NULL, + "sessionID" uuid NOT NULL, + "secureSessionID" uuid NOT NULL, + "agentIP" varchar(16) NOT NULL, + "agentPort" int NOT NULL, + "agentOnline" smallint NOT NULL, + "loginTime" int NOT NULL, + "logoutTime" int NOT NULL, + "currentRegion" uuid NOT NULL, + "currentHandle" bigint NOT NULL, + "currentPos" varchar(64) NOT NULL + ); + +INSERT INTO Tmp_agents ("UUID", "sessionID", "secureSessionID", "agentIP", "agentPort", "agentOnline", "loginTime", "logoutTime", "currentRegion", "currentHandle", "currentPos") + SELECT cast("UUID" as uuid), cast("sessionID" as uuid), cast("secureSessionID" as uuid), "agentIP", "agentPort", "agentOnline", "loginTime", "logoutTime", cast("currentRegion" as uuid), "currentHandle", "currentPos" + FROM agents ; + +DROP TABLE agents; + +alter table Tmp_agents rename to agents; + +ALTER TABLE agents ADD CONSTRAINT + PK__agents__65A475E749C3F6B7 PRIMARY KEY + ( + "UUID" + ) ; + +CREATE INDEX session ON agents + ( + "sessionID" + ); + +CREATE INDEX ssession ON agents + ( + "secureSessionID" + ); + +COMMIT; + + +:VERSION 8 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_userfriends + ( + "ownerID" uuid NOT NULL, + "friendID" uuid NOT NULL, + "friendPerms" int NOT NULL, + "datetimestamp" int NOT NULL + ); + +INSERT INTO Tmp_userfriends ("ownerID", "friendID", "friendPerms", "datetimestamp") + SELECT cast("ownerID" as uuid), cast( "friendID" as uuid), "friendPerms", "datetimestamp" + FROM userfriends; + +DROP TABLE userfriends; + +alter table Tmp_userfriends rename to userfriends; + +CREATE INDEX IX_userfriends_ownerID ON userfriends + ( + "ownerID" + ); + +CREATE INDEX IX_userfriends_friendID ON userfriends + ( + "friendID" + ); + +COMMIT; + + +:VERSION 9 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_avatarappearance + ( + "Owner" uuid NOT NULL, + "Serial" int NOT NULL, + "Visual_Params" bytea NOT NULL, + "Texture" bytea NOT NULL, + "Avatar_Height" double precision NOT NULL, + "Body_Item" uuid NOT NULL, + "Body_Asset" uuid NOT NULL, + "Skin_Item" uuid NOT NULL, + "Skin_Asset" uuid NOT NULL, + "Hair_Item" uuid NOT NULL, + "Hair_Asset" uuid NOT NULL, + "Eyes_Item" uuid NOT NULL, + "Eyes_Asset" uuid NOT NULL, + "Shirt_Item" uuid NOT NULL, + "Shirt_Asset" uuid NOT NULL, + "Pants_Item" uuid NOT NULL, + "Pants_Asset" uuid NOT NULL, + "Shoes_Item" uuid NOT NULL, + "Shoes_Asset" uuid NOT NULL, + "Socks_Item" uuid NOT NULL, + "Socks_Asset" uuid NOT NULL, + "Jacket_Item" uuid NOT NULL, + "Jacket_Asset" uuid NOT NULL, + "Gloves_Item" uuid NOT NULL, + "Gloves_Asset" uuid NOT NULL, + "Undershirt_Item" uuid NOT NULL, + "Undershirt_Asset" uuid NOT NULL, + "Underpants_Item" uuid NOT NULL, + "Underpants_Asset" uuid NOT NULL, + "Skirt_Item" uuid NOT NULL, + "Skirt_Asset" uuid NOT NULL + ); + +INSERT INTO Tmp_avatarappearance ("Owner", "Serial", "Visual_Params", "Texture", "Avatar_Height", "Body_Item", "Body_Asset", "Skin_Item", "Skin_Asset", "Hair_Item", "Hair_Asset", "Eyes_Item", "Eyes_Asset", "Shirt_Item", "Shirt_Asset", "Pants_Item", "Pants_Asset", "Shoes_Item", "Shoes_Asset", "Socks_Item", "Socks_Asset", "Jacket_Item", "Jacket_Asset", "Gloves_Item", "Gloves_Asset", "Undershirt_Item", "Undershirt_Asset", "Underpants_Item", "Underpants_Asset", "Skirt_Item", "Skirt_Asset") + SELECT cast("Owner" as uuid), "Serial", "Visual_Params", "Texture", "Avatar_Height", cast("Body_Item" as uuid), cast("Body_Asset" as uuid), cast("Skin_Item" as uuid), cast("Skin_Asset" as uuid), cast("Hair_Item" as uuid), cast("Hair_Asset" as uuid), cast("Eyes_Item" as uuid), cast("Eyes_Asset" as uuid), cast("Shirt_Item" as uuid), cast("Shirt_Asset" as uuid), cast("Pants_Item" as uuid), cast("Pants_Asset" as uuid), cast("Shoes_Item" as uuid), cast("Shoes_Asset" as uuid), cast("Socks_Item" as uuid), cast("Socks_Asset" as uuid), cast("Jacket_Item" as uuid), cast("Jacket_Asset" as uuid), cast("Gloves_Item" as uuid), cast("Gloves_Asset" as uuid), cast("Undershirt_Item" as uuid), cast("Undershirt_Asset" as uuid), cast("Underpants_Item" as uuid), cast("Underpants_Asset" as uuid), cast("Skirt_Item" as uuid), cast("Skirt_Asset" as uuid) + FROM avatarappearance ; + +DROP TABLE avatarappearance; + +alter table Tmp_avatarappearance rename to avatarappearance; + +ALTER TABLE avatarappearance ADD CONSTRAINT + PK__avatarap__7DD115CC4E88ABD4 PRIMARY KEY + ( + "Owner" + ); + +COMMIT; + + +:VERSION 10 + +BEGIN TRANSACTION; + +CREATE TABLE Tmp_avatarattachments + ( + "UUID" uuid NOT NULL, + "attachpoint" int NOT NULL, + item uuid NOT NULL, + asset uuid NOT NULL + ); + +INSERT INTO Tmp_avatarattachments ("UUID", "attachpoint", item, asset) + SELECT cast("UUID" as uuid), "attachpoint", cast(item as uuid), cast(asset as uuid) + FROM avatarattachments ; + +DROP TABLE avatarattachments; + +alter table Tmp_avatarattachments rename to avatarattachments; + +CREATE INDEX IX_avatarattachments ON avatarattachments + ( + "UUID" + ); + +COMMIT; + + +:VERSION 11 + +BEGIN TRANSACTION; + +ALTER TABLE users ADD "scopeID" uuid not null default '00000000-0000-0000-0000-000000000000'; + +COMMIT; diff --git a/OpenSim/Data/PGSQL/Resources/XAssetStore.migrations b/OpenSim/Data/PGSQL/Resources/XAssetStore.migrations new file mode 100644 index 0000000000..325ed0d520 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/XAssetStore.migrations @@ -0,0 +1,27 @@ +# ----------------- +:VERSION 1 + +BEGIN; + +CREATE TABLE XAssetsMeta ( + "ID" char(36) NOT NULL, + "Hash" char(32) NOT NULL, + "Name" varchar(64) NOT NULL, + "Description" varchar(64) NOT NULL, + "AssetType" smallint NOT NULL, + "Local" smallint NOT NULL, + "Temporary" smallint NOT NULL, + "CreateTime" integer NOT NULL, + "AccessTime" integer NOT NULL, + "AssetFlags" integer NOT NULL, + "CreatorID" varchar(128) NOT NULL, + PRIMARY KEY ("ID") +); + +CREATE TABLE XAssetsData ( + "Hash" char(32) NOT NULL, + "Data" bytea NOT NULL, + PRIMARY KEY ("Hash") +); + +COMMIT; diff --git a/OpenSim/Data/PGSQL/Resources/os_groups_Store.migrations b/OpenSim/Data/PGSQL/Resources/os_groups_Store.migrations new file mode 100644 index 0000000000..4573f71311 --- /dev/null +++ b/OpenSim/Data/PGSQL/Resources/os_groups_Store.migrations @@ -0,0 +1,94 @@ +:VERSION 1 # -------------------------- + +BEGIN; + +CREATE TABLE os_groups_groups ( + "GroupID" char(36) Primary Key NOT NULL default '', + "Location" varchar(255) NOT NULL default '', + "Name" varchar(255) NOT NULL default '', + "Charter" text NOT NULL, + "InsigniaID" char(36) NOT NULL default '', + "FounderID" char(36) NOT NULL default '', + "MembershipFee" integer NOT NULL default '0', + "OpenEnrollment" varchar(255) NOT NULL default '', + "ShowInList" integer NOT NULL default '0', + "AllowPublish" integer NOT NULL default '0', + "MaturePublish" integer NOT NULL default '0', + "OwnerRoleID" char(36) NOT NULL default '' +); + + +CREATE TABLE os_groups_membership ( + "GroupID"char(36) NOT NULL default '', + "PrincipalID" VARCHAR(255) NOT NULL default '', + "SelectedRoleID" char(36) NOT NULL default '', + "Contribution" integer NOT NULL default '0', + "ListInProfile" integer NOT NULL default '1', + "AcceptNotices" integer NOT NULL default '1', + "AccessToken" char(36) NOT NULL default '', + constraint os_groupmemberpk primary key ("GroupID", "PrincipalID") +); + + + +CREATE TABLE os_groups_roles ( + "GroupID" char(36) NOT NULL default '', + "RoleID" char(36) NOT NULL default '', + "Name" varchar(255) NOT NULL default '', + "Description" varchar(255) NOT NULL default '', + "Title" varchar(255) NOT NULL default '', + "Powers" bigint NOT NULL default 0, + constraint os_grouprolepk PRIMARY KEY ("GroupID","RoleID") +); + + +CREATE TABLE os_groups_rolemembership ( + "GroupID" char(36) NOT NULL default '', + "RoleID" char(36) NOT NULL default '', + "PrincipalID" VARCHAR(255) NOT NULL default '', + constraint os_grouprolememberpk PRIMARY KEY ("GroupID","RoleID","PrincipalID") +); + + +CREATE TABLE os_groups_invites ( + "InviteID" char(36) NOT NULL default '', + "GroupID" char(36) NOT NULL default '', + "RoleID" char(36) NOT NULL default '', + "PrincipalID" VARCHAR(255) NOT NULL default '', + "TMStamp" timestamp NOT NULL default now(), + constraint os_groupinvitespk PRIMARY KEY ("InviteID") +); +-- UNIQUE KEY "PrincipalGroup" ("GroupID","PrincipalID") + + +CREATE TABLE os_groups_notices ( + "GroupID" char(36) NOT NULL default '', + "NoticeID" char(36) NOT NULL default '', + "TMStamp" integer NOT NULL default '0', + "FromName" varchar(255) NOT NULL default '', + "Subject" varchar(255) NOT NULL default '', + "Message" text NOT NULL, + "HasAttachment" integer NOT NULL default '0', + "AttachmentType" integer NOT NULL default '0', + "AttachmentName" varchar(128) NOT NULL default '', + "AttachmentItemID" char(36) NOT NULL default '', + "AttachmentOwnerID" varchar(255) NOT NULL default '', + constraint os_groupsnoticespk PRIMARY KEY ("NoticeID") +); +-- KEY "GroupID" ("GroupID"), +-- KEY "TMStamp" ("TMStamp") + +CREATE TABLE os_groups_principals ( + "PrincipalID" VARCHAR(255) NOT NULL default '', + "ActiveGroupID" char(36) NOT NULL default '', + constraint os_groupprincpk PRIMARY KEY ("PrincipalID") +); + +COMMIT; + +:VERSION 2 # -------------------------- + +BEGIN; + + +COMMIT; diff --git a/bin/Npgsql.dll b/bin/Npgsql.dll new file mode 100644 index 0000000000..24ca4bde64 Binary files /dev/null and b/bin/Npgsql.dll differ diff --git a/bin/Npgsql.xml b/bin/Npgsql.xml new file mode 100644 index 0000000000..a51252d119 --- /dev/null +++ b/bin/Npgsql.xml @@ -0,0 +1,4120 @@ + + + + Npgsql + + + + + This class represents a parameter to a command that will be sent to server + + + + + Initializes a new instance of the NpgsqlParameter class. + + + + + Initializes a new instance of the NpgsqlParameter + class with the parameter m_Name and a value of the new NpgsqlParameter. + + The m_Name of the parameter to map. + An Object that is the value of the NpgsqlParameter. + +

When you specify an Object + in the value parameter, the DbType is + inferred from the .NET Framework type of the Object.

+

When using this constructor, you must be aware of a possible misuse of the constructor which takes a DbType parameter. + This happens when calling this constructor passing an int 0 and the compiler thinks you are passing a value of DbType. + Use Convert.ToInt32(value) for example to have compiler calling the correct constructor.

+
+
+ + + Initializes a new instance of the NpgsqlParameter + class with the parameter m_Name and the data type. + + The m_Name of the parameter to map. + One of the DbType values. + + + + Initializes a new instance of the NpgsqlParameter + class with the parameter m_Name, the DbType, and the size. + + The m_Name of the parameter to map. + One of the DbType values. + The length of the parameter. + + + + Initializes a new instance of the NpgsqlParameter + class with the parameter m_Name, the DbType, the size, + and the source column m_Name. + + The m_Name of the parameter to map. + One of the DbType values. + The length of the parameter. + The m_Name of the source column. + + + + Initializes a new instance of the NpgsqlParameter + class with the parameter m_Name, the DbType, the size, + the source column m_Name, a ParameterDirection, + the precision of the parameter, the scale of the parameter, a + DataRowVersion to use, and the + value of the parameter. + + The m_Name of the parameter to map. + One of the DbType values. + The length of the parameter. + The m_Name of the source column. + One of the ParameterDirection values. + true if the value of the field can be null, otherwise false. + The total number of digits to the left and right of the decimal point to which + Value is resolved. + The total number of decimal places to which + Value is resolved. + One of the DataRowVersion values. + An Object that is the value + of the NpgsqlParameter. + + + + Creates a new NpgsqlParameter that + is a copy of the current instance. + + A new NpgsqlParameter that is a copy of this instance. + + + + Gets or sets the maximum number of digits used to represent the + Value property. + + The maximum number of digits used to represent the + Value property. + The default value is 0, which indicates that the data provider + sets the precision for Value. + + + + Gets or sets the number of decimal places to which + Value is resolved. + + The number of decimal places to which + Value is resolved. The default is 0. + + + + Gets or sets the maximum size, in bytes, of the data within the column. + + The maximum size, in bytes, of the data within the column. + The default value is inferred from the parameter value. + + + + Gets or sets the DbType of the parameter. + + One of the DbType values. The default is String. + + + + Gets or sets the DbType of the parameter. + + One of the DbType values. The default is String. + + + + Gets or sets a value indicating whether the parameter is input-only, + output-only, bidirectional, or a stored procedure return value parameter. + + One of the ParameterDirection + values. The default is Input. + + + + Gets or sets a value indicating whether the parameter accepts null values. + + true if null values are accepted; otherwise, false. The default is false. + + + + Gets or sets the m_Name of the NpgsqlParameter. + + The m_Name of the NpgsqlParameter. + The default is an empty string. + + + + The m_Name scrubbed of any optional marker + + + + + Gets or sets the m_Name of the source column that is mapped to the + DataSet and used for loading or + returning the Value. + + The m_Name of the source column that is mapped to the + DataSet. The default is an empty string. + + + + Gets or sets the DataRowVersion + to use when loading Value. + + One of the DataRowVersion values. + The default is Current. + + + + Gets or sets the value of the parameter. + + An Object that is the value of the parameter. + The default value is null. + + + + Gets or sets the value of the parameter. + + An Object that is the value of the parameter. + The default value is null. + + + + This class represents the Parse message sent to PostgreSQL + server. + + + + + + For classes representing messages sent from the client to the server. + + + + + Writes given objects into a stream for PostgreSQL COPY in default copy format (not CSV or BINARY). + + + + + Return an exact copy of this NpgsqlConnectionString. + + + + + This function will set value for known key, both private member and base[key]. + + + + + + + The function will modify private member only, not base[key]. + + + + + + + Clear the member and assign them to the default value. + + + + + Compatibilty version. When possible, behaviour caused by breaking changes will be preserved + if this version is less than that where the breaking change was introduced. + + + + + Case insensative accessor for indivual connection string values. + + + + + Common base class for all derived MD5 implementations. + + + + + Called from constructor of derived class. + + + + + Finalizer for HashAlgorithm + + + + + Computes the entire hash of all the bytes in the byte array. + + + + + When overridden in a derived class, drives the hashing function. + + + + + + + + When overridden in a derived class, this pads and hashes whatever data might be left in the buffers and then returns the hash created. + + + + + When overridden in a derived class, initializes the object to prepare for hashing. + + + + + Used for stream chaining. Computes hash as data passes through it. + + The buffer from which to grab the data to be copied. + The offset into the input buffer to start reading at. + The number of bytes to be copied. + The buffer to write the copied data to. + At what point in the outputBuffer to write the data at. + + + + Used for stream chaining. Computes hash as data passes through it. Finishes off the hash. + + The buffer from which to grab the data to be copied. + The offset into the input buffer to start reading at. + The number of bytes to be copied. + + + + Get whether or not the hash can transform multiple blocks at a time. + Note: MUST be overriden if descendant can transform multiple block + on a single call! + + + + + Gets the previously computed hash. + + + + + Returns the size in bits of the hash. + + + + + Must be overriden if not 1 + + + + + Must be overriden if not 1 + + + + + Called from constructor of derived class. + + + + + Creates the default derived class. + + + + + Given a join expression and a projection, fetch all columns in the projection + that reference columns in the join. + + + + + Given an InputExpression append all from names (including nested joins) to the list. + + + + + Get new ColumnExpression that will be used in projection that had it's existing columns moved. + These should be simple references to the inner column + + + + + Every property accessed in the list of columns must be adjusted for a new scope + + + + + This class provides many util methods to handle + reading and writing of PostgreSQL protocol messages. + + + + + This method takes a ProtocolVersion and returns an integer + version number that the Postgres backend will recognize in a + startup packet. + + + + + This method takes a version string as returned by SELECT VERSION() and returns + a valid version string ("7.2.2" for example). + This is only needed when running protocol version 2. + This does not do any validity checks. + + + + + This method gets a C NULL terminated string from the network stream. + It keeps reading a byte in each time until a NULL byte is returned. + It returns the resultant string of bytes read. + This string is sent from backend. + + + + + Reads requested number of bytes from stream with retries until Stream.Read returns 0 or count is reached. + + Stream to read + byte buffer to fill + starting position to fill the buffer + number of bytes to read + The number of bytes read. May be less than count if no more bytes are available. + + + + This method writes a C NULL terminated string to the network stream. + It appends a NULL terminator to the end of the String. + + + This method writes a C NULL terminated string to the network stream. + It appends a NULL terminator to the end of the String. + + + + + This method writes a set of bytes to the stream. It also enables logging of them. + + + + + This method writes a C NULL terminated string limited in length to the + backend server. + It pads the string with null bytes to the size specified. + + + + + Write a 32-bit integer to the given stream in the correct byte order. + + + + + Read a 32-bit integer from the given stream in the correct byte order. + + + + + Write a 16-bit integer to the given stream in the correct byte order. + + + + + Read a 16-bit integer from the given stream in the correct byte order. + + + + + Represent the frontend/backend protocol version. + + + + + Represent the backend server version. + As this class offers no functionality beyond that offered by it has been + deprecated in favour of that class. + + + + + + Returns the string representation of this version in three place dot notation (Major.Minor.Patch). + + + + + Server version major number. + + + + + Server version minor number. + + + + + Server version patch level number. + + + + + Represents a PostgreSQL COPY TO STDOUT operation with a corresponding SQL statement + to execute against a PostgreSQL database + and an associated stream used to write results to (if provided by user) + or for reading the results (when generated by driver). + Eg. new NpgsqlCopyOut("COPY (SELECT * FROM mytable) TO STDOUT", connection, streamToWrite).Start(); + + + + + Creates NpgsqlCommand to run given query upon Start(), after which CopyStream provides data from database as requested in the query. + + + + + Given command is run upon Start(), after which CopyStream provides data from database as requested in the query. + + + + + Given command is executed upon Start() and all requested copy data is written to toStream immediately. + + + + + Returns true if this operation is currently active and field at given location is in binary format. + + + + + Command specified upon creation is executed as a non-query. + If CopyStream is set upon creation, all copy data from server will be written to it, and operation will be finished immediately. + Otherwise the CopyStream member can be used for reading copy data from server until no more data is available. + + + + + Flush generated CopyStream at once. Effectively reads and discard all the rest of copy data from server. + + + + + Returns true if the connection is currently reserved for this operation. + + + + + The stream provided by user or generated upon Start() + + + + + The Command used to execute this copy operation. + + + + + Returns true if this operation is currently active and in binary format. + + + + + Returns number of fields if this operation is currently active, otherwise -1 + + + + + Faster alternative to using the generated CopyStream. + + + + + This class manages all connector objects, pooled AND non-pooled. + + + + Unique static instance of the connector pool + mamager. + + + Map of index to unused pooled connectors, avaliable to the + next RequestConnector() call. + This hashmap will be indexed by connection string. + This key will hold a list of queues of pooled connectors available to be used. + + + Timer for tracking unused connections in pools. + + + + Searches the shared and pooled connector lists for a + matching connector object or creates a new one. + + The NpgsqlConnection that is requesting + the connector. Its ConnectionString will be used to search the + pool for available connectors. + A connector object. + + + + Find a pooled connector. Handle locking and timeout here. + + + + + Find a pooled connector. Handle shared/non-shared here. + + + + + Releases a connector, possibly back to the pool for future use. + + + Pooled connectors will be put back into the pool if there is room. + Shared connectors should just have their use count decremented + since they always stay in the shared pool. + + The connector to release. + + + + Release a pooled connector. Handle locking here. + + + + + Release a pooled connector. Handle shared/non-shared here. + + + + + Create a connector without any pooling functionality. + + + + + Find an available pooled connector in the non-shared pool, or create + a new one if none found. + + + + + This method is only called when NpgsqlConnection.Dispose(false) is called which means a + finalization. This also means, an NpgsqlConnection was leak. We clear pool count so that + client doesn't end running out of connections from pool. When the connection is finalized, its underlying + socket is closed. + + + + + Close the connector. + + + Connector to release + + + + Put a pooled connector into the pool queue. + + Connector to pool + + + + A queue with an extra Int32 for keeping track of busy connections. + + + + + Connections available to the end user + + + + + Connections currently in use + + + + + This class represents a BackEndKeyData message received + from PostgreSQL + + + + + Used when a connection is closed + + + + + Summary description for NpgsqlQuery + + + + + Represents the method that handles the Notice events. + + A NpgsqlNoticeEventArgs that contains the event data. + + + + Represents the method that handles the Notification events. + + The source of the event. + A NpgsqlNotificationEventArgs that contains the event data. + + + + This class represents a connection to a + PostgreSQL server. + + + + + Initializes a new instance of the + NpgsqlConnection class. + + + + + Initializes a new instance of the + NpgsqlConnection class + and sets the ConnectionString. + + The connection used to open the PostgreSQL database. + + + + Begins a database transaction with the specified isolation level. + + The isolation level under which the transaction should run. + An DbTransaction + object representing the new transaction. + + Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend. + There's no support for nested transactions. + + + + + Begins a database transaction. + + A NpgsqlTransaction + object representing the new transaction. + + Currently there's no support for nested transactions. + + + + + Begins a database transaction with the specified isolation level. + + The isolation level under which the transaction should run. + A NpgsqlTransaction + object representing the new transaction. + + Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend. + There's no support for nested transactions. + + + + + Opens a database connection with the property settings specified by the + ConnectionString. + + + + + This method changes the current database by disconnecting from the actual + database and connecting to the specified. + + The name of the database to use in place of the current database. + + + + Releases the connection to the database. If the connection is pooled, it will be + made available for re-use. If it is non-pooled, the actual connection will be shutdown. + + + + + Creates and returns a DbCommand + object associated with the IDbConnection. + + A DbCommand object. + + + + Creates and returns a NpgsqlCommand + object associated with the NpgsqlConnection. + + A NpgsqlCommand object. + + + + Releases all resources used by the + NpgsqlConnection. + + true when called from Dispose(); + false when being called from the finalizer. + + + + Create a new connection based on this one. + + A new NpgsqlConnection object. + + + + Create a new connection based on this one. + + A new NpgsqlConnection object. + + + + Default SSL CertificateSelectionCallback implementation. + + + + + Default SSL CertificateValidationCallback implementation. + + + + + Default SSL PrivateKeySelectionCallback implementation. + + + + + Default SSL ProvideClientCertificatesCallback implementation. + + + + + Write each key/value pair in the connection string to the log. + + + + + Returns the supported collections + + + + + Returns the schema collection specified by the collection name. + + The collection name. + The collection specified. + + + + Returns the schema collection specified by the collection name filtered by the restrictions. + + The collection name. + + The restriction values to filter the results. A description of the restrictions is contained + in the Restrictions collection. + + The collection specified. + + + + Occurs on NoticeResponses from the PostgreSQL backend. + + + + + Occurs on NotificationResponses from the PostgreSQL backend. + + + + + Called to provide client certificates for SSL handshake. + + + + + Mono.Security.Protocol.Tls.CertificateSelectionCallback delegate. + + + + + Mono.Security.Protocol.Tls.CertificateValidationCallback delegate. + + + + + Mono.Security.Protocol.Tls.PrivateKeySelectionCallback delegate. + + + + + Gets or sets the string used to connect to a PostgreSQL database. + Valid values are: +
    +
  • + Server: Address/Name of Postgresql Server; +
  • +
  • + Port: Port to connect to; +
  • +
  • + Protocol: Protocol version to use, instead of automatic; Integer 2 or 3; +
  • +
  • + Database: Database name. Defaults to user name if not specified; +
  • +
  • + User Id: User name; +
  • +
  • + Password: Password for clear text authentication; +
  • +
  • + SSL: True or False. Controls whether to attempt a secure connection. Default = False; +
  • +
  • + Pooling: True or False. Controls whether connection pooling is used. Default = True; +
  • +
  • + MinPoolSize: Min size of connection pool; +
  • +
  • + MaxPoolSize: Max size of connection pool; +
  • +
  • + Timeout: Time to wait for connection open in seconds. Default is 15. +
  • +
  • + CommandTimeout: Time to wait for command to finish execution before throw an exception. In seconds. Default is 20. +
  • +
  • + Sslmode: Mode for ssl connection control. Can be Prefer, Require, Allow or Disable. Default is Disable. Check user manual for explanation of values. +
  • +
  • + ConnectionLifeTime: Time to wait before closing unused connections in the pool in seconds. Default is 15. +
  • +
  • + SyncNotification: Specifies if Npgsql should use synchronous notifications. +
  • +
  • + SearchPath: Changes search path to specified and public schemas. +
  • +
+
+ The connection string that includes the server name, + the database name, and other parameters needed to establish + the initial connection. The default value is an empty string. + +
+ + + Backend server host name. + + + + + Backend server port. + + + + + If true, the connection will attempt to use SSL. + + + + + Gets the time to wait while trying to establish a connection + before terminating the attempt and generating an error. + + The time (in seconds) to wait for a connection to open. The default value is 15 seconds. + + + + Gets the time to wait while trying to execute a command + before terminating the attempt and generating an error. + + The time (in seconds) to wait for a command to complete. The default value is 20 seconds. + + + + Gets the time to wait before closing unused connections in the pool if the count + of all connections exeeds MinPoolSize. + + + If connection pool contains unused connections for ConnectionLifeTime seconds, + the half of them will be closed. If there will be unused connections in a second + later then again the half of them will be closed and so on. + This strategy provide smooth change of connection count in the pool. + + The time (in seconds) to wait. The default value is 15 seconds. + + + + Gets the name of the current database or the database to be used after a connection is opened. + + The name of the current database or the name of the database to be + used after a connection is opened. The default value is the empty string. + + + + Whether datareaders are loaded in their entirety (for compatibility with earlier code). + + + + + Gets the database server name. + + + + + Gets flag indicating if we are using Synchronous notification or not. + The default value is false. + + + + + Gets the current state of the connection. + + A bitwise combination of the ConnectionState values. The default is Closed. + + + + Gets whether the current state of the connection is Open or Closed + + ConnectionState.Open or ConnectionState.Closed + + + + Version of the PostgreSQL backend. + This can only be called when there is an active connection. + + + + + Protocol version in use. + This can only be called when there is an active connection. + + + + + Process id of backend server. + This can only be called when there is an active connection. + + + + + The connector object connected to the backend. + + + + + Gets the NpgsqlConnectionStringBuilder containing the parsed connection string values. + + + + + User name. + + + + + Password. + + + + + Determine if connection pooling will be used for this connection. + + + + + This class represents the CancelRequest message sent to PostgreSQL + server. + + + + + + + + + + + + + + + + + + + A time period expressed in 100ns units. + + + A time period expressed in a + + + Number of 100ns units. + + + Number of seconds. + + + Number of milliseconds. + + + Number of milliseconds. + + + Number of milliseconds. + + + A d with the given number of ticks. + + + A d with the given number of microseconds. + + + A d with the given number of milliseconds. + + + A d with the given number of seconds. + + + A d with the given number of minutes. + + + A d with the given number of hours. + + + A d with the given number of days. + + + A d with the given number of months. + + + An whose values are the sums of the two instances. + + + An whose values are the differences of the two instances. + + + An whose value is the negated value of this instance. + + + An whose value is the absolute value of this instance. + + + + An based on this one, but with any days converted to multiples of ±24hours. + + + + An based on this one, but with any months converted to multiples of ±30days. + + + + An based on this one, but with any months converted to multiples of ±30days and then any days converted to multiples of ±24hours; + + + + An eqivalent, canonical, . + + + An equivalent . + + + + + + An signed integer. + + + + The argument is not an . + + + The string was not in a format that could be parsed to produce an . + + + true if the parsing succeeded, false otherwise. + + + The representation. + + + An whose values are the sum of the arguments. + + + An whose values are the difference of the arguments + + + true if the two arguments are exactly the same, false otherwise. + + + false if the two arguments are exactly the same, true otherwise. + + + true if the first is less than second, false otherwise. + + + true if the first is less than or equivalent to second, false otherwise. + + + true if the first is greater than second, false otherwise. + + + true if the first is greater than or equivalent to the second, false otherwise. + + + The argument. + + + The negation of the argument. + + + + + + + + + + + + + + + + + + + + This time, normalised + + + + + + + + + This time, normalised + + + An integer which is 0 if they are equal, < 0 if this is the smaller and > 0 if this is the larger. + + + + + + + + + A class to handle everything associated with SSPI authentication + + + + + Simplified SecBufferDesc struct with only one SecBuffer + + + + + This class represents the Parse message sent to PostgreSQL + server. + + + + + + EventArgs class to send Notice parameters, which are just NpgsqlError's in a lighter context. + + + + + Notice information. + + + + + This class represents the ErrorResponse and NoticeResponse + message sent from PostgreSQL server. + + + + + Return a string representation of this error object. + + + + + Severity code. All versions. + + + + + Error code. PostgreSQL 7.4 and up. + + + + + Terse error message. All versions. + + + + + Detailed error message. PostgreSQL 7.4 and up. + + + + + Suggestion to help resolve the error. PostgreSQL 7.4 and up. + + + + + Position (one based) within the query string where the error was encounterd. PostgreSQL 7.4 and up. + + + + + Position (one based) within the query string where the error was encounterd. This position refers to an internal command executed for example inside a PL/pgSQL function. PostgreSQL 7.4 and up. + + + + + Internal query string where the error was encounterd. This position refers to an internal command executed for example inside a PL/pgSQL function. PostgreSQL 7.4 and up. + + + + + Trace back information. PostgreSQL 7.4 and up. + + + + + Source file (in backend) reporting the error. PostgreSQL 7.4 and up. + + + + + Source file line number (in backend) reporting the error. PostgreSQL 7.4 and up. + + + + + Source routine (in backend) reporting the error. PostgreSQL 7.4 and up. + + + + + String containing the sql sent which produced this error. + + + + + Backend protocol version in use. + + + + + Represents an ongoing COPY TO STDOUT operation. + Provides methods to read data from server or end the operation. + + + + This class represents the base class for the state pattern design pattern + implementation. + + + + + + This method is used by the states to change the state of the context. + + + + + This method is responsible to handle all protocol messages sent from the backend. + It holds all the logic to do it. + To exchange data, it uses a Mediator object from which it reads/writes information + to handle backend requests. + + + + + + This method is responsible to handle all protocol messages sent from the backend. + It holds all the logic to do it. + To exchange data, it uses a Mediator object from which it reads/writes information + to handle backend requests. + + + + + + Called from NpgsqlState.ProcessBackendResponses upon CopyOutResponse. + If CopyStream is already set, it is used to write data received from server, after which the copy ends. + Otherwise CopyStream is set to a readable NpgsqlCopyOutStream that receives data from server. + + + + + Called from NpgsqlOutStream.Read to read copy data from server. + + + + + Copy format information returned from server. + + + + + Handles serialisation of .NET array or IEnumeration to pg format. + Arrays of arrays, enumerations of enumerations, arrays of enumerations etc. + are treated as multi-dimensional arrays (in much the same manner as an array of arrays + is used to emulate multi-dimensional arrays in languages that lack native support for them). + If such an enumeration of enumerations is "jagged" (as opposed to rectangular, cuboid, + hypercuboid, hyperhypercuboid, etc) then this class will "correctly" serialise it, but pg + will raise an error as it doesn't allow jagged arrays. + + + + + Create an ArrayNativeToBackendTypeConverter with the element converter passed + + The that would be used to serialise the element type. + + + + Serialise the enumeration or array. + + + + + Handles parsing of pg arrays into .NET arrays. + + + + + Takes a string representation of a pg 1-dimensional array + (or a 1-dimensional row within an n-dimensional array) + and allows enumeration of the string represenations of each items. + + + + + Takes a string representation of a pg n-dimensional array + and allows enumeration of the string represenations of the next + lower level of rows (which in turn can be taken as (n-1)-dimensional arrays. + + + + + Takes an ArrayList which may be an ArrayList of ArrayLists, an ArrayList of ArrayLists of ArrayLists + and so on and enumerates the items that aren't ArrayLists (the leaf nodes if we think of the ArrayList + passed as a tree). Simply uses the ArrayLists' own IEnumerators to get that of the next, + pushing them onto a stack until we hit something that isn't an ArrayList. + ArrayList to enumerate + IEnumerable + + + + + Create a new ArrayBackendToNativeTypeConverter + + for the element type. + + + + Creates an array from pg representation. + + + + + Creates an array list from pg represenation of an array. + Multidimensional arrays are treated as ArrayLists of ArrayLists + + + + + Creates an n-dimensional array from an ArrayList of ArrayLists or + a 1-dimensional array from something else. + + to convert + produced. + + + + Takes an array of ints and treats them like the limits of a set of counters. + Retains a matching set of ints that is set to all zeros on the first ++ + On a ++ it increments the "right-most" int. If that int reaches it's + limit it is set to zero and the one before it is incremented, and so on. + + Making this a more general purpose class is pretty straight-forward, but we'll just put what we need here. + + + + + This class represents the ParameterStatus message sent from PostgreSQL + server. + + + + + + This class is responsible for serving as bridge between the backend + protocol handling and the core classes. It is used as the mediator for + exchanging data generated/sent from/to backend. + + + + + + This class is responsible to create database commands for automatic insert, update and delete operations. + + + + + + This method is reponsible to derive the command parameter list with values obtained from function definition. + It clears the Parameters collection of command. Also, if there is any parameter type which is not supported by Npgsql, an InvalidOperationException will be thrown. + Parameters name will be parameter1, parameter2, ... + For while, only parameter name and NpgsqlDbType are obtained. + + NpgsqlCommand whose function parameters will be obtained. + + + + Represents a completed response message. + + + + + + Marker interface which identifies a class which may take possession of a stream for the duration of + it's lifetime (possibly temporarily giving that possession to another class for part of that time. + + It inherits from IDisposable, since any such class must make sure it leaves the stream in a valid state. + + The most important such class is that compiler-generated from ProcessBackendResponsesEnum. Of course + we can't make that inherit from this interface, alas. + + + + + The exception that is thrown when the PostgreSQL backend reports errors. + + + + + Construct a backend error exception based on a list of one or more + backend errors. The basic Exception.Message will be built from the + first (usually the only) error in the list. + + + + + Format a .NET style exception string. + Include all errors in the list, including any hints. + + + + + Append a line to the given Stream, first checking for zero-length. + + + + + Provide access to the entire list of errors provided by the PostgreSQL backend. + + + + + Severity code. All versions. + + + + + Error code. PostgreSQL 7.4 and up. + + + + + Basic error message. All versions. + + + + + Detailed error message. PostgreSQL 7.4 and up. + + + + + Suggestion to help resolve the error. PostgreSQL 7.4 and up. + + + + + Position (one based) within the query string where the error was encounterd. PostgreSQL 7.4 and up. + + + + + Trace back information. PostgreSQL 7.4 and up. + + + + + Source file (in backend) reporting the error. PostgreSQL 7.4 and up. + + + + + Source file line number (in backend) reporting the error. PostgreSQL 7.4 and up. + + + + + Source routine (in backend) reporting the error. PostgreSQL 7.4 and up. + + + + + String containing the sql sent which produced this error. + + + + + Returns the entire list of errors provided by the PostgreSQL backend. + + + + + The level of verbosity of the NpgsqlEventLog + + + + + Don't log at all + + + + + Only log the most common issues + + + + + Log everything + + + + + This class handles all the Npgsql event and debug logging + + + + + Writes a string to the Npgsql event log if msglevel is bigger then NpgsqlEventLog.Level + + + This method is obsolete and should no longer be used. + It is likely to be removed in future versions of Npgsql + + The message to write to the event log + The minimum LogLevel for which this message should be logged. + + + + Writes a string to the Npgsql event log if msglevel is bigger then NpgsqlEventLog.Level + + The ResourceManager to get the localized resources + The name of the resource that should be fetched by the ResourceManager + The minimum LogLevel for which this message should be logged. + The additional parameters that shall be included into the log-message (must be compatible with the string in the resource): + + + + Writes the default log-message for the action of calling the Get-part of an Indexer to the log file. + + The minimum LogLevel for which this message should be logged. + The name of the class that contains the Indexer + The parameter given to the Indexer + + + + Writes the default log-message for the action of calling the Set-part of an Indexer to the logfile. + + The minimum LogLevel for which this message should be logged. + The name of the class that contains the Indexer + The parameter given to the Indexer + The value the Indexer is set to + + + + Writes the default log-message for the action of calling the Get-part of a Property to the logfile. + + The minimum LogLevel for which this message should be logged. + The name of the class that contains the Property + The name of the Property + + + + Writes the default log-message for the action of calling the Set-part of a Property to the logfile. + + The minimum LogLevel for which this message should be logged. + The name of the class that contains the Property + The name of the Property + The value the Property is set to + + + + Writes the default log-message for the action of calling a Method without Arguments to the logfile. + + The minimum LogLevel for which this message should be logged. + The name of the class that contains the Method + The name of the Method + + + + Writes the default log-message for the action of calling a Method with one Argument to the logfile. + + The minimum LogLevel for which this message should be logged. + The name of the class that contains the Method + The name of the Method + The value of the Argument of the Method + + + + Writes the default log-message for the action of calling a Method with two Arguments to the logfile. + + The minimum LogLevel for which this message should be logged. + The name of the class that contains the Method + The name of the Method + The value of the first Argument of the Method + The value of the second Argument of the Method + + + + Writes the default log-message for the action of calling a Method with three Arguments to the logfile. + + The minimum LogLevel for which this message should be logged. + The name of the class that contains the Method + The name of the Method + The value of the first Argument of the Method + The value of the second Argument of the Method + The value of the third Argument of the Method + + + + Writes the default log-message for the action of calling a Method with more than three Arguments to the logfile. + + The minimum LogLevel for which this message should be logged. + The name of the class that contains the Method + The name of the Method + A Object-Array with zero or more Ojects that are Arguments of the Method. + + + + Sets/Returns the level of information to log to the logfile. + + The current LogLevel + + + + Sets/Returns the filename to use for logging. + + The filename of the current Log file. + + + + Sets/Returns whether Log messages should be echoed to the console + + true if Log messages are echoed to the console, otherwise false + + + + This class represents the Parse message sent to PostgreSQL + server. + + + + + + Represents a PostgreSQL COPY FROM STDIN operation with a corresponding SQL statement + to execute against a PostgreSQL database + and an associated stream used to read data from (if provided by user) + or for writing it (when generated by driver). + Eg. new NpgsqlCopyIn("COPY mytable FROM STDIN", connection, streamToRead).Start(); + + + + + Creates NpgsqlCommand to run given query upon Start(). Data for the requested COPY IN operation can then be written to CopyData stream followed by a call to End() or Cancel(). + + + + + Given command is run upon Start(). Data for the requested COPY IN operation can then be written to CopyData stream followed by a call to End() or Cancel(). + + + + + Given command is executed upon Start() and all data from fromStream is passed to it as copy data. + + + + + Returns true if this operation is currently active and field at given location is in binary format. + + + + + Command specified upon creation is executed as a non-query. + If CopyStream is set upon creation, it will be flushed to server as copy data, and operation will be finished immediately. + Otherwise the CopyStream member can be used for writing copy data to server and operation finished with a call to End() or Cancel(). + + + + + Called after writing all data to CopyStream to successfully complete this copy operation. + + + + + Withdraws an already started copy operation. The operation will fail with given error message. + Will do nothing if current operation is not active. + + + + + Returns true if the connection is currently reserved for this operation. + + + + + The stream provided by user or generated upon Start(). + User may provide a stream to constructor; it is used to pass to server all data read from it. + Otherwise, call to Start() sets this to a writable NpgsqlCopyInStream that passes all data written to it to server. + In latter case this is only available while the copy operation is active and null otherwise. + + + + + Returns true if this operation is currently active and in binary format. + + + + + Returns number of fields expected on each input row if this operation is currently active, otherwise -1 + + + + + The Command used to execute this copy operation. + + + + + Set before a COPY IN query to define size of internal buffer for reading from given CopyStream. + + + + + Represents information about COPY operation data transfer format as returned by server. + + + + + Only created when a CopyInResponse or CopyOutResponse is received by NpgsqlState.ProcessBackendResponses() + + + + + Returns true if this operation is currently active and field at given location is in binary format. + + + + + Returns true if this operation is currently active and in binary format. + + + + + Returns number of fields if this operation is currently active, otherwise -1 + + + + + + + + + Provide event handlers to convert all native supported basic data types from their backend + text representation to a .NET object. + + + + + Binary data. + + + + + Convert a postgresql boolean to a System.Boolean. + + + + + Convert a postgresql bit to a System.Boolean. + + + + + Convert a postgresql datetime to a System.DateTime. + + + + + Convert a postgresql date to a System.DateTime. + + + + + Convert a postgresql time to a System.DateTime. + + + + + Convert a postgresql money to a System.Decimal. + + + + + Provide event handlers to convert the basic native supported data types from + native form to backend representation. + + + + + Binary data. + + + + + Convert to a postgresql boolean. + + + + + Convert to a postgresql bit. + + + + + Convert to a postgresql timestamp. + + + + + Convert to a postgresql date. + + + + + Convert to a postgresql time. + + + + + Convert to a postgres money. + + + + + Convert to a postgres double with maximum precision. + + + + + Provide event handlers to convert extended native supported data types from their backend + text representation to a .NET object. + + + + + Convert a postgresql point to a System.NpgsqlPoint. + + + + + Convert a postgresql point to a System.RectangleF. + + + + + LDeg. + + + + + Path. + + + + + Polygon. + + + + + Circle. + + + + + Inet. + + + + + MAC Address. + + + + + interval + + + + + Provide event handlers to convert extended native supported data types from + native form to backend representation. + + + + + Point. + + + + + Box. + + + + + LSeg. + + + + + Open path. + + + + + Polygon. + + + + + Convert to a postgres MAC Address. + + + + + Circle. + + + + + Convert to a postgres inet. + + + + + Convert to a postgres interval + + + + + EventArgs class to send Notification parameters. + + + + + Process ID of the PostgreSQL backend that sent this notification. + + + + + Condition that triggered that notification. + + + + + Additional Information From Notifiying Process (for future use, currently postgres always sets this to an empty string) + + + + + Resolve a host name or IP address. + This is needed because if you call Dns.Resolve() with an IP address, it will attempt + to resolve it as a host name, when it should just convert it to an IP address. + + + + + + This class represents a RowDescription message sent from + the PostgreSQL. + + + + + + This struct represents the internal data of the RowDescription message. + + + + + This class represents the Parse message sent to PostgreSQL + server. + + + + + + A factory to create instances of various Npgsql objects. + + + + + Creates an NpgsqlCommand object. + + + + + This class represents the Parse message sent to PostgreSQL + server. + + + + + + Represents the method that handles the RowUpdated events. + + The source of the event. + A NpgsqlRowUpdatedEventArgs that contains the event data. + + + + Represents the method that handles the RowUpdating events. + + The source of the event. + A NpgsqlRowUpdatingEventArgs that contains the event data. + + + + This class represents an adapter from many commands: select, update, insert and delete to fill Datasets. + + + + + Stream for reading data from a table or select on a PostgreSQL version 7.4 or newer database during an active COPY TO STDOUT operation. + Passes data exactly as provided by the server. + + + + + Created only by NpgsqlCopyOutState.StartCopy() + + + + + Discards copy data as long as server pushes it. Returns after operation is finished. + Does nothing if this stream is not the active copy operation reader. + + + + + Not writable. + + + + + Not flushable. + + + + + Copies data read from server to given byte buffer. + Since server returns data row by row, length will differ each time, but it is only zero once the operation ends. + Can be mixed with calls to the more efficient NpgsqlCopyOutStream.Read() : byte[] though that would not make much sense. + + + + + Not seekable + + + + + Not supported + + + + + Returns a whole row of data from server without extra work. + If standard Stream.Read(...) has been called before, it's internal buffers remains are returned. + + + + + True while this stream can be used to read copy data from server + + + + + True + + + + + False + + + + + False + + + + + Number of bytes read so far + + + + + Number of bytes read so far; can not be set. + + + + + This class represents the Bind message sent to PostgreSQL + server. + + + + + + Summary description for LargeObjectManager. + + + + + Represents a transaction to be made in a PostgreSQL database. This class cannot be inherited. + + + + + Commits the database transaction. + + + + + Rolls back a transaction from a pending state. + + + + + Rolls back a transaction from a pending savepoint state. + + + + + Creates a transaction save point. + + + + + Cancel the transaction without telling the backend about it. This is + used to make the transaction go away when closing a connection. + + + + + Gets the NpgsqlConnection + object associated with the transaction, or a null reference if the + transaction is no longer valid. + + The NpgsqlConnection + object associated with the transaction. + + + + Specifies the IsolationLevel for this transaction. + + The IsolationLevel for this transaction. + The default is ReadCommitted. + + + + This class represents a StartupPacket message of PostgreSQL + protocol. + + + + + + Provides a means of reading a forward-only stream of rows from a PostgreSQL backend. This class cannot be inherited. + + + + + Return the data type name of the column at index . + + + + + Return the data type of the column at index . + + + + + Return the Npgsql specific data type of the column at requested ordinal. + + column position + Appropriate Npgsql type for column. + + + + Return the column name of the column at index . + + + + + Return the data type OID of the column at index . + + FIXME: Why this method returns String? + + + + Return the column name of the column named . + + + + + Return the data DbType of the column at index . + + + + + Return the data NpgsqlDbType of the column at index . + + + + + Get the value of a column as a . + If the differences between and + in handling of days and months is not important to your application, use + instead. + + Index of the field to find. + value of the field. + + + + Gets the value of a column converted to a Guid. + + + + + Gets the value of a column as Int16. + + + + + Gets the value of a column as Int32. + + + + + Gets the value of a column as Int64. + + + + + Gets the value of a column as Single. + + + + + Gets the value of a column as Double. + + + + + Gets the value of a column as String. + + + + + Gets the value of a column as Decimal. + + + + + Gets the value of a column as TimeSpan. + + + + + Copy values from each column in the current row into . + + The number of column values copied. + + + + Copy values from each column in the current row into . + + An array appropriately sized to store values from all columns. + The number of column values copied. + + + + Gets the value of a column as Boolean. + + + + + Gets the value of a column as Byte. Not implemented. + + + + + Gets the value of a column as Char. + + + + + Gets the value of a column as DateTime. + + + + + Returns a System.Data.DataTable that describes the column metadata of the DataReader. + + + + + This methods parses the command text and tries to get the tablename + from it. + + + + + Is raised whenever Close() is called. + + + + + Gets the number of columns in the current row. + + + + + Gets the value of a column in its native format. + + + + + Gets the value of a column in its native format. + + + + + Gets a value indicating the depth of nesting for the current row. Always returns zero. + + + + + Gets a value indicating whether the data reader is closed. + + + + + Contains the column names as the keys + + + + + Contains all unique columns + + + + + This is the primary implementation of NpgsqlDataReader. It is the one used in normal cases (where the + preload-reader option is not set in the connection string to resolve some potential backwards-compatibility + issues), the only implementation used internally, and in cases where CachingDataReader is used, it is still + used to do the actual "leg-work" of turning a response stream from the server into a datareader-style + object - with CachingDataReader then filling it's cache from here. + + + + + Iterate through the objects returned through from the server. + If it's a CompletedResponse the rowsaffected count is updated appropriately, + and we iterate again, otherwise we return it (perhaps updating our cache of pending + rows if appropriate). + + The next we will deal with. + + + + Advances the data reader to the next result, when multiple result sets were returned by the PostgreSQL backend. + + True if the reader was advanced, otherwise false. + + + + Releases the resources used by the NpgsqlCommand. + + + + + Closes the data reader object. + + + + + Advances the data reader to the next result, when multiple result sets were returned by the PostgreSQL backend. + + True if the reader was advanced, otherwise false. + + + + Advances the data reader to the next row. + + True if the reader was advanced, otherwise false. + + + + Return the value of the column at index . + + + + + Gets raw data from a column. + + + + + Gets raw data from a column. + + + + + Report whether the value in a column is DBNull. + + + + + Gets the number of rows changed, inserted, or deleted by execution of the SQL statement. + + + + + Indicates if NpgsqlDatareader has rows to be read. + + + + + Provides an implementation of NpgsqlDataReader in which all data is pre-loaded into memory. + This operates by first creating a ForwardsOnlyDataReader as usual, and then loading all of it's + Rows into memory. There is a general principle that when there is a trade-off between a class design that + is more efficient and/or scalable on the one hand and one that is less efficient but has more functionality + (in this case the internal-only functionality of caching results) that one can build the less efficent class + from the most efficient without significant extra loss in efficiency, but not the other way around. The relationship + between ForwardsOnlyDataReader and CachingDataReader is an example of this). + Since the interface presented to the user is still forwards-only, queues are used to + store this information, so that dequeueing as we go we give the garbage collector the best opportunity + possible to reclaim any memory that is no longer in use. + ForwardsOnlyDataReader being used to actually + obtain the information from the server means that the "leg-work" is still only done (and need only be + maintained) in one place. + This class exists to allow for certain potential backwards-compatibility issues to be resolved + with little effort on the part of affected users. It is considerably less efficient than ForwardsOnlyDataReader + and hence never used internally. + + + + + Represents the method that allows the application to provide a certificate collection to be used for SSL clien authentication + + A X509CertificateCollection to be filled with one or more client certificates. + + + + !!! Helper class, for compilation only. + Connector implements the logic for the Connection Objects to + access the physical connection to the database, and isolate + the application developer from connection pooling internals. + + + + + Constructor. + + Controls whether the connector can be shared. + + + + This method checks if the connector is still ok. + We try to send a simple query text, select 1 as ConnectionTest; + + + + + This method is responsible for releasing all resources associated with this Connector. + + + + + This method is responsible to release all portals used by this Connector. + + + + + Default SSL CertificateSelectionCallback implementation. + + + + + Default SSL CertificateValidationCallback implementation. + + + + + Default SSL PrivateKeySelectionCallback implementation. + + + + + Default SSL ProvideClientCertificatesCallback implementation. + + + + + This method is required to set all the version dependent features flags. + SupportsPrepare means the server can use prepared query plans (7.3+) + + + + + Opens the physical connection to the server. + + Usually called by the RequestConnector + Method of the connection pool manager. + + + + Closes the physical connection to the server. + + + + + Returns next portal index. + + + + + Returns next plan index. + + + + + Occurs on NoticeResponses from the PostgreSQL backend. + + + + + Occurs on NotificationResponses from the PostgreSQL backend. + + + + + Called to provide client certificates for SSL handshake. + + + + + Mono.Security.Protocol.Tls.CertificateSelectionCallback delegate. + + + + + Mono.Security.Protocol.Tls.CertificateValidationCallback delegate. + + + + + Mono.Security.Protocol.Tls.PrivateKeySelectionCallback delegate. + + + + + Gets the current state of the connection. + + + + + Return Connection String. + + + + + Version of backend server this connector is connected to. + + + + + Backend protocol version in use by this connector. + + + + + The physical connection stream to the backend. + + + + + The physical connection socket to the backend. + + + + + Reports if this connector is fully connected. + + + + + The connection mediator. + + + + + Report if the connection is in a transaction. + + + + + Report whether the current connection can support prepare functionality. + + + + + This class contains helper methods for type conversion between + the .Net type system and postgresql. + + + + + A cache of basic datatype mappings keyed by server version. This way we don't + have to load the basic type mappings for every connection. + + + + + Find a NpgsqlNativeTypeInfo in the default types map that can handle objects + of the given NpgsqlDbType. + + + + + Find a NpgsqlNativeTypeInfo in the default types map that can handle objects + of the given NpgsqlDbType. + + + + + Find a NpgsqlNativeTypeInfo in the default types map that can handle objects + of the given DbType. + + + + + Find a NpgsqlNativeTypeInfo in the default types map that can handle objects + of the given System.Type. + + + + + This method is responsible to convert the string received from the backend + to the corresponding NpgsqlType. + The given TypeInfo is called upon to do the conversion. + If no TypeInfo object is provided, no conversion is performed. + + + + + Create the one and only native to backend type map. + This map is used when formatting native data + types to backend representations. + + + + + This method creates (or retrieves from cache) a mapping between type and OID + of all natively supported postgresql data types. + This is needed as from one version to another, this mapping can be changed and + so we avoid hardcoding them. + + NpgsqlTypeMapping containing all known data types. The mapping must be + cloned before it is modified because it is cached; changes made by one connection may + effect another connection. + + + + Attempt to map types by issuing a query against pg_type. + This function takes a list of NpgsqlTypeInfo and attempts to resolve the OID field + of each by querying pg_type. If the mapping is found, the type info object is + updated (OID) and added to the provided NpgsqlTypeMapping object. + + NpgsqlConnector to send query through. + Mapping object to add types too. + List of types that need to have OID's mapped. + + + + Delegate called to convert the given backend data to its native representation. + + + + + Delegate called to convert the given native data to its backand representation. + + + + + Represents a backend data type. + This class can be called upon to convert a backend field representation to a native object. + + + + + Construct a new NpgsqlTypeInfo with the given attributes and conversion handlers. + + Type OID provided by the backend server. + Type name provided by the backend server. + NpgsqlDbType + System type to convert fields of this type to. + Data conversion handler. + + + + Perform a data conversion from a backend representation to + a native object. + + Data sent from the backend. + Type modifier field sent from the backend. + + + + Type OID provided by the backend server. + + + + + Type name provided by the backend server. + + + + + NpgsqlDbType. + + + + + NpgsqlDbType. + + + + + Provider type to convert fields of this type to. + + + + + System type to convert fields of this type to. + + + + + Represents a backend data type. + This class can be called upon to convert a native object to its backend field representation, + + + + + Returns an NpgsqlNativeTypeInfo for an array where the elements are of the type + described by the NpgsqlNativeTypeInfo supplied. + + + + + Construct a new NpgsqlTypeInfo with the given attributes and conversion handlers. + + Type name provided by the backend server. + NpgsqlDbType + Data conversion handler. + + + + Perform a data conversion from a native object to + a backend representation. + DBNull and null values are handled differently depending if a plain query is used + When + + Native .NET object to be converted. + Flag indicating if the conversion has to be done for + plain queries or extended queries + + + + Type name provided by the backend server. + + + + + NpgsqlDbType. + + + + + DbType. + + + + + Apply quoting. + + + + + Use parameter size information. + + + + + Provide mapping between type OID, type name, and a NpgsqlBackendTypeInfo object that represents it. + + + + + Construct an empty mapping. + + + + + Copy constuctor. + + + + + Add the given NpgsqlBackendTypeInfo to this mapping. + + + + + Add a new NpgsqlBackendTypeInfo with the given attributes and conversion handlers to this mapping. + + Type OID provided by the backend server. + Type name provided by the backend server. + NpgsqlDbType + System type to convert fields of this type to. + Data conversion handler. + + + + Make a shallow copy of this type mapping. + + + + + Determine if a NpgsqlBackendTypeInfo with the given backend type OID exists in this mapping. + + + + + Determine if a NpgsqlBackendTypeInfo with the given backend type name exists in this mapping. + + + + + Get the number of type infos held. + + + + + Retrieve the NpgsqlBackendTypeInfo with the given backend type OID, or null if none found. + + + + + Retrieve the NpgsqlBackendTypeInfo with the given backend type name, or null if none found. + + + + + Provide mapping between type Type, NpgsqlDbType and a NpgsqlNativeTypeInfo object that represents it. + + + + + Add the given NpgsqlNativeTypeInfo to this mapping. + + + + + Add a new NpgsqlNativeTypeInfo with the given attributes and conversion handlers to this mapping. + + Type name provided by the backend server. + NpgsqlDbType + Data conversion handler. + + + + Retrieve the NpgsqlNativeTypeInfo with the given NpgsqlDbType. + + + + + Retrieve the NpgsqlNativeTypeInfo with the given DbType. + + + + + Retrieve the NpgsqlNativeTypeInfo with the given Type. + + + + + Determine if a NpgsqlNativeTypeInfo with the given backend type name exists in this mapping. + + + + + Determine if a NpgsqlNativeTypeInfo with the given NpgsqlDbType exists in this mapping. + + + + + Determine if a NpgsqlNativeTypeInfo with the given Type name exists in this mapping. + + + + + Get the number of type infos held. + + + + + Implements for version 3 of the protocol. + + + + + Reads a row, field by field, allowing a DataRow to be built appropriately. + + + + + Reads part of a field, as needed (for + and + + + + + Adds further functionality to stream that is dependant upon the type of data read. + + + + + Completes the implementation of Streamer for char data. + + + + + Completes the implementation of Streamer for byte data. + + + + + Implements for version 2 of the protocol. + + + + + Encapsulates the null mapping bytes sent at the start of a version 2 + datarow message, and the process of identifying the nullity of the data + at a particular index + + + + + Provides the underlying mechanism for reading schema information. + + + + + Creates an NpgsqlSchema that can read schema information from the database. + + An open database connection for reading metadata. + + + + Returns the MetaDataCollections that lists all possible collections. + + The MetaDataCollections + + + + Returns the Restrictions that contains the meaning and position of the values in the restrictions array. + + The Restrictions + + + + Returns the Databases that contains a list of all accessable databases. + + The restrictions to filter the collection. + The Databases + + + + Returns the Tables that contains table and view names and the database and schema they come from. + + The restrictions to filter the collection. + The Tables + + + + Returns the Columns that contains information about columns in tables. + + The restrictions to filter the collection. + The Columns. + + + + Returns the Views that contains view names and the database and schema they come from. + + The restrictions to filter the collection. + The Views + + + + Returns the Users containing user names and the sysid of those users. + + The restrictions to filter the collection. + The Users. + + + + This is the abstract base class for NpgsqlAsciiRow and NpgsqlBinaryRow. + + + + + Implements a bit string; a collection of zero or more bits which can each be 1 or 0. + BitString's behave as a list of bools, though like most strings and unlike most collections the position + tends to be of as much significance as the value. + BitStrings are often used as masks, and are commonly cast to and from other values. + + + + + Represents the empty string. + + + + + Create a BitString from an enumeration of boolean values. The BitString will contain + those booleans in the order they came in. + + The boolean values. + + + + Creates a BitString filled with a given number of true or false values. + + The value to fill the string with. + The number of bits to fill. + + + + Creats a bitstring from a string. + The string to copy from. + + + + + + Creates a single-bit element from a boolean value. + + The bool value which determines whether + the bit is 1 or 0. + + + + Creates a bitstring from an unsigned integer value. The string will be the shortest required to + contain the integer (e.g. 1 bit for 0 or 1, 2 for 2 or 3, 3 for 4-7, and so on). + + The integer. + This method is not CLS Compliant, and may not be available to some languages. + + + + Creates a bitstring from an integer value. The string will be the shortest required to + contain the integer (e.g. 1 bit for 0 or 1, 2 for 2 or 3, 3 for 4-7, and so on). + + The integer. + + + + Finds the first instance of a given value + + The value - whether true or false - to search for. + The index of the value found, or -1 if none are present. + + + + True if there is at least one bit with the value looked for. + + The value - true or false - to detect. + True if at least one bit was the same as item, false otherwise. + + + + Copies the bitstring to an array of bools. + + The boolean array to copy to. + The index in the array to start copying from. + + + + Returns an enumerator that enumerates through the string. + + The enumerator. + + + + Creats a bitstring by concatenating another onto this one. + + The string to append to this one. + The combined strings. + + + + Returns a substring of this string. + + The position to start from, must be between 0 and the length of the string. + The length of the string to return, must be greater than zero, and may not be + so large that the start + length exceeds the bounds of this instance. + The Bitstring identified + + + + Returns a substring of this string. + + The position to start from, must be between 0 and the length of the string, + the rest of the string is returned. + The Bitstring identified + + + + A logical and between this string and another. The two strings must be the same length. + + Another BitString to AND with this one. + A bitstring with 1 where both BitStrings had 1 and 0 otherwise. + + + + A logical or between this string and another. The two strings must be the same length. + + Another BitString to OR with this one. + A bitstring with 1 where either BitString had 1 and 0 otherwise. + + + + A logical xor between this string and another. The two strings must be the same length. + + Another BitString to XOR with this one. + A bitstring with 1 where one BitStrings and the other had 0, + and 0 where they both had 1 or both had 0. + + + + A bitstring that is the logical inverse of this one. + + A bitstring of the same length as this with 1 where this has 0 and vice-versa. + + + + Shifts the string operand bits to the left, filling with zeros to produce a + string of the same length. + + The number of bits to shift to the left. + A left-shifted bitstring. + The behaviour of LShift is closer to what one would expect from dealing + with PostgreSQL bit-strings than in using the same operations on integers in .NET + In particular, negative operands result in a right-shift, and operands greater than + the length of the string will shift it entirely, resulting in a zero-filled string. + + + + + Shifts the string operand bits to the right, filling with zeros to produce a + string of the same length. + + The number of bits to shift to the right. + A right-shifted bitstring. + The behaviour of RShift is closer to what one would expect from dealing + with PostgreSQL bit-strings than in using the same operations on integers in .NET + In particular, negative operands result in a left-shift, and operands greater than + the length of the string will shift it entirely, resulting in a zero-filled string. It also performs + a logical shift, rather than an arithmetic shift, so it always sets the vacated bit positions to zero + (like PostgreSQL and like .NET for unsigned integers but not for signed integers). + + + + + Returns true if the this string is identical to the argument passed. + + + + + Compares two strings. Strings are compared as strings, so while 0 being less than 1 will + mean a comparison between two strings of the same size is the same as treating them as numbers, + in the case of two strings of differing lengths the comparison starts at the right-most (most significant) + bit, and if all bits of the shorter string are exhausted without finding a comparison, then the larger + string is deemed to be greater than the shorter (0010 is greater than 0001 but less than 00100). + + Another string to compare with this one. + A value if the two strings are identical, an integer less + than zero if this is less than the argument, and an integer greater + than zero otherwise. + + + + Compares the string with another object. + + The object to compare with. + If the object is null then this string is considered greater. If the object is another BitString + then they are compared as in the explicit comparison for BitStrings + in any other case a is thrown. + + + + Compares this BitString with an object for equality. + + + + + Returns a code for use in hashing operations. + + + + + Returns a string representation of the BitString. + + + A string which can contain a letter and optionally a number which sets a minimum size for the string + returned. In each case using the lower-case form of the letter will result in a lower-case string + being returned. + + + B + A string of 1s and 0s. + + + X + An hexadecimal string (will result in an error unless the string's length is divisible by 4). + + + G + A string of 1s and 0s in single-quotes preceded by 'B' (Postgres bit string literal syntax). + + Y + An hexadecimal string in single-quotes preceded by 'X' (Postgres bit literal syntax, will result in an error unless the string's length is divisible by 4. + + C + The format produced by format-string "Y" if legal, otherwise that produced by format-string "G". + E + The most compact safe representation for Postgres. If single bit will be either a 0 or a 1. Otherwise if it + can be that produce by format string "Y" it will, otherwise if there are less than 9bits in length it will be that + produced by format-string "G". For longer strings that cannot be represented in hexadecimal it will be a string + representing the first part of the string in format "Y" followed by the PostgreSQL concatenation operator, followed + by the final bits in the format "G". E.g. "X'13DCE'||B'110'" + If format is empty or null, it is treated as if "B" had been passed (the default repreesentation, and that + generally used by PostgreSQL for display). + + The formatted string. + + + + Returns a string representation for the Bitstring + + A string containing '0' and '1' characters. + + + + Returns the same string as . formatProvider is ignored. + + + + + Parses a string to produce a BitString. Most formats that can be produced by + can be accepted, but hexadecimal + can be interpreted with the preceding X' to mark the following characters as + being hexadecimal rather than binary. + + + + + Performs a logical AND on the two operands. + + + + + Performs a logcial OR on the two operands. + + + + + Perofrms a logical EXCLUSIVE-OR on the two operands + + + + + Performs a logical NOT on the operand. + + + + + Concatenates the operands. + + + + + Left-shifts the string BitString. + + + + + Right-shifts the string BitString. + + + + + Compares the two operands. + + + + + Compares the two operands. + + + + + Compares the two operands. + + + + + Compares the two operands. + + + + + Compares the two operands. + + + + + Compares the two operands. + + + + + Interprets the bitstring as a series of bits in an encoded character string, + encoded according to the Encoding passed, and returns that string. + The bitstring must contain a whole number of octets(bytes) and also be + valid according to the Encoding passed. + + The to use in producing the string. + The string that was encoded in the BitString. + + + + Interprets the bitstring as a series of octets (bytes) and returns those octets. Fails + if the Bitstring does not contain a whole number of octets (its length is not evenly + divisible by 8). + + + + + Interprets the bitstring as a series of signed octets (bytes) and returns those octets. Fails + if the Bitstring does not contain a whole number of octets (its length is not evenly + divisible by 8). + This method is not CLS-Compliant and may not be available to languages that cannot + handle signed bytes. + + + + + Interprets the bitstring as a series of unsigned 16-bit integers and returns those integers. + Fails if the Bitstring's length is not evenly divisible by 16. + This method is not CLS-Compliant and may not be available to languages that cannot + handle unsigned integers. + + + + + Interprets the bitstring as a series of 16-bit integers and returns those integers. + Fails if the Bitstring's length is not evenly divisible by 16. + + + + + Interprets the bitstring as a series of unsigned 32-bit integers and returns those integers. + Fails if the Bitstring's length is not evenly divisible by 32. + This method is not CLS-Compliant and may not be available to languages that cannot + handle unsigned integers. + + + + + Interprets the bitstring as a series of signed 32-bit integers and returns those integers. + Fails if the Bitstring's length is not evenly divisible by 32. + + + + + Interprets the bitstring as a series of unsigned 64-bit integers and returns those integers. + Fails if the Bitstring's length is not evenly divisible by 64. + This method is not CLS-Compliant and may not be available to languages that cannot + handle unsigned integers. + + + + + Interprets the bitstring as a series of signed 64-bit integers and returns those integers. + Fails if the Bitstring's length is not evenly divisible by 64. + + + + + The length of the string. + + + + + Retrieves the value of the bit at the given index. + + + + + C# implementation of the MD5 cryptographic hash function. + + + + + Creates a new MD5CryptoServiceProvider. + + + + + Drives the hashing function. + + Byte array containing the data to hash. + Where in the input buffer to start. + Size in bytes of the data in the buffer to hash. + + + + This finalizes the hash. Takes the data from the chaining variables and returns it. + + + + + Resets the class after use. Called automatically after hashing is done. + + + + + This is the meat of the hash function. It is what processes each block one at a time. + + Byte array to process data from. + Where in the byte array to start processing. + + + + Pads and then processes the final block. + + Buffer to grab data from. + Position in buffer in bytes to get data from. + How much data in bytes in the buffer to use. + + + + Stream for writing data to a table on a PostgreSQL version 7.4 or newer database during an active COPY FROM STDIN operation. + Passes data exactly as is and when given, so see to it that you use server encoding, correct format and reasonably sized writes! + + + + + Created only by NpgsqlCopyInState.StartCopy() + + + + + Successfully completes copying data to server. Returns after operation is finished. + Does nothing if this stream is not the active copy operation writer. + + + + + Withdraws an already started copy operation. The operation will fail with given error message. + Does nothing if this stream is not the active copy operation writer. + + + + + Writes given bytes to server. + Fails if this stream is not the active copy operation writer. + + + + + Flushes stream contents to server. + Fails if this stream is not the active copy operation writer. + + + + + Not readable + + + + + Not seekable + + + + + Not supported + + + + + True while this stream can be used to write copy data to server + + + + + False + + + + + True + + + + + False + + + + + Number of bytes written so far + + + + + Number of bytes written so far; not settable + + + + + Represents a SQL statement or function (stored procedure) to execute + against a PostgreSQL database. This class cannot be inherited. + + + + + Initializes a new instance of the NpgsqlCommand class. + + + + + Initializes a new instance of the NpgsqlCommand class with the text of the query. + + The text of the query. + + + + Initializes a new instance of the NpgsqlCommand class with the text of the query and a NpgsqlConnection. + + The text of the query. + A NpgsqlConnection that represents the connection to a PostgreSQL server. + + + + Initializes a new instance of the NpgsqlCommand class with the text of the query, a NpgsqlConnection, and the NpgsqlTransaction. + + The text of the query. + A NpgsqlConnection that represents the connection to a PostgreSQL server. + The NpgsqlTransaction in which the NpgsqlCommand executes. + + + + Used to execute internal commands. + + + + + Attempts to cancel the execution of a NpgsqlCommand. + + This Method isn't implemented yet. + + + + Create a new command based on this one. + + A new NpgsqlCommand object. + + + + Create a new command based on this one. + + A new NpgsqlCommand object. + + + + Creates a new instance of an DbParameter object. + + An DbParameter object. + + + + Creates a new instance of a NpgsqlParameter object. + + A NpgsqlParameter object. + + + + Slightly optimised version of ExecuteNonQuery() for internal ues in cases where the number + of affected rows is of no interest. + + + + + Executes a SQL statement against the connection and returns the number of rows affected. + + The number of rows affected if known; -1 otherwise. + + + + Sends the CommandText to + the Connection and builds a + NpgsqlDataReader + using one of the CommandBehavior values. + + One of the CommandBehavior values. + A NpgsqlDataReader object. + + + + Sends the CommandText to + the Connection and builds a + NpgsqlDataReader. + + A NpgsqlDataReader object. + + + + Sends the CommandText to + the Connection and builds a + NpgsqlDataReader + using one of the CommandBehavior values. + + One of the CommandBehavior values. + A NpgsqlDataReader object. + Currently the CommandBehavior parameter is ignored. + + + + This method binds the parameters from parameters collection to the bind + message. + + + + + Executes the query, and returns the first column of the first row + in the result set returned by the query. Extra columns or rows are ignored. + + The first column of the first row in the result set, + or a null reference if the result set is empty. + + + + Creates a prepared version of the command on a PostgreSQL server. + + + + + This method checks the connection state to see if the connection + is set or it is open. If one of this conditions is not met, throws + an InvalidOperationException + + + + + This method substitutes the Parameters, if exist, in the command + to their actual values. + The parameter name format is :ParameterName. + + A version of CommandText with the Parameters inserted. + + + + Gets or sets the SQL statement or function (stored procedure) to execute at the data source. + + The Transact-SQL statement or stored procedure to execute. The default is an empty string. + + + + Gets or sets the wait time before terminating the attempt + to execute a command and generating an error. + + The time (in seconds) to wait for the command to execute. + The default is 20 seconds. + + + + Gets or sets a value indicating how the + CommandText property is to be interpreted. + + One of the CommandType values. The default is CommandType.Text. + + + + Gets or sets the NpgsqlConnection + used by this instance of the NpgsqlCommand. + + The connection to a data source. The default value is a null reference. + + + + Gets the NpgsqlParameterCollection. + + The parameters of the SQL statement or function (stored procedure). The default is an empty collection. + + + + Gets or sets the NpgsqlTransaction + within which the NpgsqlCommand executes. + + The NpgsqlTransaction. + The default value is a null reference. + + + + Gets or sets how command results are applied to the DataRow + when used by the Update + method of the DbDataAdapter. + + One of the UpdateRowSource values. + + + + Returns oid of inserted row. This is only updated when using executenonQuery and when command inserts just a single row. If table is created without oids, this will always be 0. + + + + + Represents a collection of parameters relevant to a NpgsqlCommand + as well as their respective mappings to columns in a DataSet. + This class cannot be inherited. + + + + + Initializes a new instance of the NpgsqlParameterCollection class. + + + + + Adds the specified NpgsqlParameter object to the NpgsqlParameterCollection. + + The NpgsqlParameter to add to the collection. + The index of the new NpgsqlParameter object. + + + + Adds a NpgsqlParameter to the NpgsqlParameterCollection given the specified parameter name and value. + + The name of the NpgsqlParameter. + The Value of the NpgsqlParameter to add to the collection. + The index of the new NpgsqlParameter object. + + Use caution when using this overload of the + Add method to specify integer parameter values. + Because this overload takes a value of type Object, + you must convert the integral value to an Object + type when the value is zero, as the following C# example demonstrates. + parameters.Add(":pname", Convert.ToInt32(0)); + If you do not perform this conversion, the compiler will assume you + are attempting to call the NpgsqlParameterCollection.Add(string, DbType) overload. + + + + + Adds a NpgsqlParameter to the NpgsqlParameterCollection given the parameter name and the data type. + + The name of the parameter. + One of the DbType values. + The index of the new NpgsqlParameter object. + + + + Adds a NpgsqlParameter to the NpgsqlParameterCollection with the parameter name, the data type, and the column length. + + The name of the parameter. + One of the DbType values. + The length of the column. + The index of the new NpgsqlParameter object. + + + + Adds a NpgsqlParameter to the NpgsqlParameterCollection with the parameter name, the data type, the column length, and the source column name. + + The name of the parameter. + One of the DbType values. + The length of the column. + The name of the source column. + The index of the new NpgsqlParameter object. + + + + Removes the specified NpgsqlParameter from the collection using the parameter name. + + The name of the NpgsqlParameter object to retrieve. + + + + Gets a value indicating whether a NpgsqlParameter with the specified parameter name exists in the collection. + + The name of the NpgsqlParameter object to find. + true if the collection contains the parameter; otherwise, false. + + + + Gets the location of the NpgsqlParameter in the collection with a specific parameter name. + + The name of the NpgsqlParameter object to find. + The zero-based location of the NpgsqlParameter in the collection. + + + + Removes the specified NpgsqlParameter from the collection using a specific index. + + The zero-based index of the parameter. + + + + Inserts a NpgsqlParameter into the collection at the specified index. + + The zero-based index where the parameter is to be inserted within the collection. + The NpgsqlParameter to add to the collection. + + + + Removes the specified NpgsqlParameter from the collection. + + The NpgsqlParameter to remove from the collection. + + + + Gets a value indicating whether a NpgsqlParameter exists in the collection. + + The value of the NpgsqlParameter object to find. + true if the collection contains the NpgsqlParameter object; otherwise, false. + + + + Gets a value indicating whether a NpgsqlParameter with the specified parameter name exists in the collection. + + The name of the NpgsqlParameter object to find. + A reference to the requested parameter is returned in this out param if it is found in the list. This value is null if the parameter is not found. + true if the collection contains the parameter and param will contain the parameter; otherwise, false. + + + + Removes all items from the collection. + + + + + Gets the location of a NpgsqlParameter in the collection. + + The value of the NpgsqlParameter object to find. + The zero-based index of the NpgsqlParameter object in the collection. + + + + Adds the specified NpgsqlParameter object to the NpgsqlParameterCollection. + + The NpgsqlParameter to add to the collection. + The zero-based index of the new NpgsqlParameter object. + + + + Copies NpgsqlParameter objects from the NpgsqlParameterCollection to the specified array. + + An Array to which to copy the NpgsqlParameter objects in the collection. + The starting index of the array. + + + + Returns an enumerator that can iterate through the collection. + + An IEnumerator that can be used to iterate through the collection. + + + + In methods taking an object as argument this method is used to verify + that the argument has the type NpgsqlParameter + + The object to verify + + + + Gets the NpgsqlParameter with the specified name. + + The name of the NpgsqlParameter to retrieve. + The NpgsqlParameter with the specified name, or a null reference if the parameter is not found. + + + + Gets the NpgsqlParameter at the specified index. + + The zero-based index of the NpgsqlParameter to retrieve. + The NpgsqlParameter at the specified index. + + + + Gets the number of NpgsqlParameter objects in the collection. + + The number of NpgsqlParameter objects in the collection. + + + + Represents an ongoing COPY FROM STDIN operation. + Provides methods to push data to server and end or cancel the operation. + + + + + Called from NpgsqlState.ProcessBackendResponses upon CopyInResponse. + If CopyStream is already set, it is used to read data to push to server, after which the copy is completed. + Otherwise CopyStream is set to a writable NpgsqlCopyInStream that calls SendCopyData each time it is written to. + + + + + Sends given packet to server as a CopyData message. + Does not check for notifications! Use another thread for that. + + + + + Sends CopyDone message to server. Handles responses, ie. may throw an exception. + + + + + Sends CopyFail message to server. Handles responses, ie. should always throw an exception: + in CopyIn state the server responds to CopyFail with an error response; + outside of a CopyIn state the server responds to CopyFail with an error response; + without network connection or whatever, there's going to eventually be a failure, timeout or user intervention. + + + + + Copy format information returned from server. + + + + + Represents a PostgreSQL Point type + + + + + Represents a PostgreSQL Line Segment type. + + + + + Represents a PostgreSQL Path type. + + + + + Represents a PostgreSQL Polygon type. + + + + + Represents a PostgreSQL Circle type. + + + + + Represents a PostgreSQL inet type. + + + + + Represents a PostgreSQL MacAddress type. + + + + + + + The macAddr parameter must contain a string that can only consist of numbers + and upper-case letters as hexadecimal digits. (See PhysicalAddress.Parse method on MSDN) + + + + This class represents a PasswordPacket message sent to backend + PostgreSQL. + + +
+
diff --git a/bin/Robust.HG.ini.example b/bin/Robust.HG.ini.example index 8fe6d0c990..2ad262ae4f 100644 --- a/bin/Robust.HG.ini.example +++ b/bin/Robust.HG.ini.example @@ -126,6 +126,15 @@ HGAssetServiceConnector = "HGAssetService@8002/OpenSim.Server.Handlers.dll:Asset ; GatekeeperURI = "http://127.0.0.1:8002" [DatabaseService] + ; PGSQL + ; Uncomment these lines if you want to use PGSQL storage + ; Change the connection string to your db details + ;StorageProvider = "OpenSim.Data.PGSQL.dll" + ;ConnectionString = "Server=localhost;Database=opensim;User Id=opensim; password=***;" + + ; MySQL + ; Uncomment these lines if you want to use MySQL storage + ; Change the connection string to your db details StorageProvider = "OpenSim.Data.MySQL.dll" ConnectionString = "Data Source=localhost;Database=opensim;User ID=opensim;Password=*****;Old Guids=true;" diff --git a/bin/Robust.ini.example b/bin/Robust.ini.example index 74c208dd60..6a84574759 100644 --- a/bin/Robust.ini.example +++ b/bin/Robust.ini.example @@ -88,6 +88,15 @@ MapGetServiceConnector = "8002/OpenSim.Server.Handlers.dll:MapGetServiceConnecto ;ConsolePort = 0 [DatabaseService] + ; PGSQL + ; Uncomment these lines if you want to use PGSQL storage + ; Change the connection string to your db details + ;StorageProvider = "OpenSim.Data.PGSQL.dll" + ;ConnectionString = "Server=localhost;Database=opensim;User Id=opensim; password=***;" + + ; MySQL + ; Uncomment these lines if you want to use MySQL storage + ; Change the connection string to your db details StorageProvider = "OpenSim.Data.MySQL.dll" ConnectionString = "Data Source=localhost;Database=opensim;User ID=opensim;Password=*****;Old Guids=true;" diff --git a/bin/config-include/GridCommon.ini.example b/bin/config-include/GridCommon.ini.example index 0a69dbf67d..5460c0a0f0 100644 --- a/bin/config-include/GridCommon.ini.example +++ b/bin/config-include/GridCommon.ini.example @@ -26,6 +26,12 @@ ;StorageProvider = "OpenSim.Data.MSSQL.dll" ;ConnectionString = "Server=localhost\SQLEXPRESS;Database=opensim;User Id=opensim; password=***;" + ; PGSQL + ; Uncomment these lines if you want to use PGSQL storage + ; Change the connection string to your db details + ;StorageProvider = "OpenSim.Data.PGSQL.dll" + ;ConnectionString = "Server=localhost;Database=opensim;User Id=opensim; password=***;" + [Hypergrid] ; Uncomment the variables in this section only if you are in ; Hypergrid configuration. Otherwise, ignore. diff --git a/bin/config-include/StandaloneCommon.ini.example b/bin/config-include/StandaloneCommon.ini.example index 75fd956d04..ef4fb3ccbc 100644 --- a/bin/config-include/StandaloneCommon.ini.example +++ b/bin/config-include/StandaloneCommon.ini.example @@ -27,6 +27,12 @@ ;StorageProvider = "OpenSim.Data.MSSQL.dll" ;ConnectionString = "Server=localhost\SQLEXPRESS;Database=opensim;User Id=opensim; password=***;" + ; PGSQL + ; Uncomment these lines if you want to use PGSQL storage + ; Change the connection string to your db details + ;StorageProvider = "OpenSim.Data.PGSQL.dll" + ;ConnectionString = "Server=localhost;Database=opensim;User Id=opensim; password=***;" + [Hypergrid] ; Uncomment the variables in this section only if you are in ; Hypergrid configuration. Otherwise, ignore. diff --git a/prebuild.xml b/prebuild.xml index 585f96deb0..a5357da16d 100644 --- a/prebuild.xml +++ b/prebuild.xml @@ -2073,6 +2073,42 @@ + + + + ../../../bin/ + + + + + ../../../bin/ + + + + ../../../bin/ + + + + + + + + + + + + + + + + + + + + + + +