Remove the SQLite and PGSQL Connectors. We'll provide support for them via the ef core models. Clean up references to them and fix a few more logging references.

This commit is contained in:
Mike Dickson 2024-06-12 22:20:22 -04:00
parent 393e013a63
commit 5753772bb1
93 changed files with 57 additions and 20225 deletions

View file

@ -12,5 +12,11 @@
<Version>0.9.3.0</Version>
<AssemblyVersion>0.9.3.0</AssemblyVersion>
<FileVersion>0.9.3.0</FileVersion>
</PropertyGroup>
</Project>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Nerdbank.GitVersioning" Condition="!Exists('packages.config')">
<PrivateAssets>all</PrivateAssets>
<Version>3.6.133</Version>
</PackageReference>
</ItemGroup>
</Project>

View file

@ -50,15 +50,8 @@
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\GloebitSubscriptionsMySQL.migrations" />
<EmbeddedResource Include="Resources\GloebitSubscriptionsPGSQL.migrations" />
<EmbeddedResource Include="Resources\GloebitSubscriptionsSQLite.migrations" />
<EmbeddedResource Include="Resources\GloebitTransactionsMySQL.migrations" />
<EmbeddedResource Include="Resources\GloebitTransactionsPGSQL.migrations" />
<EmbeddedResource Include="Resources\GloebitTransactionsSQLite.migrations" />
<EmbeddedResource Include="Resources\GloebitUsersMySQL.migrations" />
<EmbeddedResource Include="Resources\GloebitUsersPGSQL.migrations" />
<EmbeddedResource Include="Resources\GloebitUsersSQLite.migrations" />
<EmbeddedResource Include="Resources\Gloebit.addin.xml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="8.0.0" />

View file

@ -16,14 +16,10 @@
* along with OpenSim-MoneyModule-Gloebit. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using OpenSim.Data.MySQL;
using OpenSim.Data.PGSQL;
using OpenSim.Data.SQLite;
using Npgsql;
using NpgsqlTypes;
using OpenMetaverse; // Necessary for UUID type
@ -37,15 +33,9 @@ namespace Gloebit.GloebitMoneyModule
public static void Initialise(string storageProvider, string connectionString) {
switch(storageProvider) {
case "OpenSim.Data.SQLite.dll":
m_impl = new SQLiteImpl(connectionString);
break;
case "OpenSim.Data.MySQL.dll":
m_impl = new MySQLImpl(connectionString);
break;
case "OpenSim.Data.PGSQL.dll":
m_impl = new PGSQLImpl(connectionString);
break;
default:
break;
}
@ -65,21 +55,6 @@ namespace Gloebit.GloebitMoneyModule
bool UpdateFromGloebit(GloebitSubscription subscription);
}
private class SQLiteImpl : SQLiteGenericTableHandler<GloebitSubscription>, IGloebitSubscriptionData {
public SQLiteImpl(string connectionString)
: base(connectionString, "GloebitSubscriptions", "GloebitSubscriptionsSQLite")
{
}
/// TODO: Likely need to override Store() function to handle bools, DateTimes and nulls.
/// Start with SQLiteGenericTableHandler impl and see MySql override below
public bool UpdateFromGloebit(GloebitSubscription subscription) {
// TODO: may need a similar treatment to PGSQL
return Store(subscription);
}
}
private class MySQLImpl : MySQLGenericTableHandler<GloebitSubscription>, IGloebitSubscriptionData {
public MySQLImpl(string connectionString)
: base(connectionString, "GloebitSubscriptions", "GloebitSubscriptionsMySQL")
@ -142,215 +117,5 @@ namespace Gloebit.GloebitMoneyModule
}
}
}
private class PGSQLImpl : PGSQLGenericTableHandler<GloebitSubscription>, IGloebitSubscriptionData {
public PGSQLImpl(string connectionString)
: base(connectionString, "GloebitSubscriptions", "GloebitSubscriptionsPGSQL")
{
}
public bool UpdateFromGloebit(GloebitSubscription subscription) {
// set Enabled=subscription.Enabled and SubscriptionID=subscription.SubscriptionID)
//// UPDATE GloebitSubscriptions
//// SET SubscriptionID=val, Enabled=val
//// WHERE ObjectID=val AND AppKey=val AND GlbApiUrl=Val
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
// Build Query Structure
StringBuilder query = new StringBuilder();
query.AppendFormat("UPDATE {0} ", m_Realm);
query.AppendFormat("SET \"{0}\" = :{0}, \"{1}\" = :{1} ", "SubscriptionID", "Enabled");
query.AppendFormat("WHERE \"{0}\" = :{0} AND \"{1}\" = :{1} AND \"{2}\" = :{2}", "ObjectID", "AppKey", "GlbApiUrl");
// Add parameters we are going to set or use in where clause
string pgFieldType = "";
string[] pList = new string[5] {"SubscriptionID", "Enabled", "ObjectID", "AppKey", "GlbApiUrl"};
foreach (FieldInfo fi in m_Fields.Values) {
// if (pList.Contains(fi.Name)) { --- Can't use Contains before .NET 3.5
if (Array.Exists(pList, delegate(string s) { return s.Equals(fi.Name); })) {
if (m_FieldTypes.ContainsKey(fi.Name)) {
pgFieldType = m_FieldTypes[fi.Name];
} else {
pgFieldType = "";
}
cmd.Parameters.Add(createParameter(fi.Name, fi.GetValue(subscription), pgFieldType, true));
}
}
// Execute query
cmd.Connection = conn;
cmd.CommandText = query.ToString();
conn.Open();
if (cmd.ExecuteNonQuery() > 0) {
//m_log.Info("[PGSQLGenericTable]: UpdateFromGloebit completed successfully");
return true;
} else {
//m_log.Error("[PGSQLGenericTable]: UpdateFromGloebit FAILED!!!!!");
return false;
}
}
}
private NpgsqlParameter createParameter(string pName, object pValue, string pgFieldType, bool input) {
//HACK if object is null, it is turned into a string, there are no nullable type till now
if (pValue == null) pValue = "";
NpgsqlDbType dbType = dbtypeFromString(pValue.GetType(), pgFieldType);
NpgsqlParameter parameter = new NpgsqlParameter(pName, dbType);
if (input) {
parameter.Direction = ParameterDirection.Input;
// TODO: convert cpv to use dbType instead of pgFieldType
parameter.Value = createParameterValue(pValue, pgFieldType);
} else {
parameter.Direction = ParameterDirection.Output;
}
return parameter;
}
private 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);
}
private 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;
}
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(bool))
{
return (bool)value;
}
return value;
}
private 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;
}
if (PGFieldType == "double precision")
{
return Convert.ToDouble(value);
}
return createParameterValue(value);
}
}
}
}

View file

@ -23,7 +23,6 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenSim.Data.MySQL;
using OpenSim.Data.PGSQL;
using OpenSim.Server.Base;
using MySqlConnector;
@ -40,15 +39,9 @@ namespace Gloebit.GloebitMoneyModule
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<GloebitTransactionData>>();
switch (storageProvider) {
case "OpenSim.Data.SQLite.dll":
m_impl = new SQLiteImpl(connectionString);
break;
case "OpenSim.Data.MySQL.dll":
m_impl = new MySQLImpl(connectionString);
break;
case "OpenSim.Data.PGSQL.dll":
m_impl = new PGSQLImpl(connectionString);
break;
default:
break;
}
@ -66,26 +59,6 @@ namespace Gloebit.GloebitMoneyModule
bool Store(GloebitTransaction txn);
}
private class SQLiteImpl : SQLiteGenericTableHandler<GloebitTransaction>, IGloebitTransactionData {
public SQLiteImpl(string connectionString)
: base(connectionString, "GloebitTransactions", "GloebitTransactionsSQLite")
{
}
public override bool Store(GloebitTransaction txn)
{
// remove null datetimes as pgsql throws exceptions on null fields
if (txn.enactedTime == null) {
txn.enactedTime = SqlDateTime.MinValue.Value;
}
if (txn.finishedTime == null) {
txn.finishedTime = SqlDateTime.MinValue.Value;
}
// call parent
return base.Store(txn);
}
}
private class MySQLImpl : MySQLGenericTableHandler<GloebitTransaction>, IGloebitTransactionData {
public MySQLImpl(string connectionString)
: base(connectionString, "GloebitTransactions", "GloebitTransactionsMySQL")
@ -153,37 +126,5 @@ namespace Gloebit.GloebitMoneyModule
}
}
private class PGSQLImpl : PGSQLGenericTableHandler<GloebitTransaction>, IGloebitTransactionData {
private static ILogger m_logger;
public PGSQLImpl(string connectionString)
: base(connectionString, "GloebitTransactions", "GloebitTransactionsPGSQL")
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<PGSQLImpl>>();
}
public override bool Store(GloebitTransaction txn)
{
try {
// remove null datetimes as pgsql throws exceptions on null fields
if (txn.enactedTime == null) {
txn.enactedTime = SqlDateTime.MinValue.Value;
}
if (txn.finishedTime == null) {
txn.finishedTime = SqlDateTime.MinValue.Value;
}
//m_log.InfoFormat("GloebitTransactionData.PGSQLImpl: storing transaction type:{0}, SaleType:{2}, PayerEndingBalance:{3}, cTime:{4}, enactedTime:{5}, finishedTime:{6}", txn.TransactionType, txn.SaleType, txn.PayerEndingBalance, txn.cTime, txn.enactedTime, txn.finishedTime);
// call parent
return base.Store(txn);
} catch(System.OverflowException e) {
m_logger.LogError("GloebitTransactionData.PGSQLImpl: Failure storing transaction type:{0}, SaleType:{1}, PayerEndingBalance:{2}, cTime:{3}, enactedTime:{4}, finishedTime:{5}, stacktrace:{6}", txn.TransactionType, txn.SaleType, txn.PayerEndingBalance, txn.cTime, txn.enactedTime, txn.finishedTime, e);
return false;
} catch(Exception e) {
m_logger.LogDebug("[PGSQL GENERIC TABLE HANDLER]: Failed to store data: {0}", e);
return false;
}
}
}
}
}

View file

@ -16,13 +16,7 @@
* along with OpenSim-MoneyModule-Gloebit. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using Nini.Config;
using MySqlConnector;
using OpenSim.Data.MySQL;
using OpenSim.Data.PGSQL;
using OpenSim.Data.SQLite;
namespace Gloebit.GloebitMoneyModule
{
@ -32,15 +26,9 @@ namespace Gloebit.GloebitMoneyModule
public static void Initialise(string storageProvider, string connectionString) {
switch(storageProvider) {
case "OpenSim.Data.SQLite.dll":
m_impl = new SQLiteImpl(connectionString);
break;
case "OpenSim.Data.MySQL.dll":
m_impl = new MySQLImpl(connectionString);
break;
case "OpenSim.Data.PGSQL.dll":
m_impl = new PGSQLImpl(connectionString);
break;
default:
break;
}
@ -58,25 +46,11 @@ namespace Gloebit.GloebitMoneyModule
bool Store(GloebitUser user);
}
private class SQLiteImpl : SQLiteGenericTableHandler<GloebitUser>, IGloebitUserData {
public SQLiteImpl(string connectionString)
: base(connectionString, "GloebitUsers", "GloebitUsersSQLite")
{
}
}
private class MySQLImpl : MySQLGenericTableHandler<GloebitUser>, IGloebitUserData {
public MySQLImpl(string connectionString)
: base(connectionString, "GloebitUsers", "GloebitUsersMySQL")
{
}
}
private class PGSQLImpl : PGSQLGenericTableHandler<GloebitUser>, IGloebitUserData {
public PGSQLImpl(string connectionString)
: base(connectionString, "GloebitUsers", "GloebitUsersPGSQL")
{
}
}
}
}

View file

@ -23,8 +23,6 @@
<Reference name="MySql.Data" path="../../../bin/"/>
<Reference name="OpenSim.Data"/>
<Reference name="OpenSim.Data.MySQL"/>
<Reference name="OpenSim.Data.PGSQL"/>
<Reference name="OpenSim.Data.SQLite"/>
<Reference name="OpenSim.Framework"/>
<Reference name="OpenSim.Framework.Servers"/>
<Reference name="OpenSim.Framework.Servers.HttpServer"/>

View file

@ -25,8 +25,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@ -46,7 +44,7 @@ namespace OpenSim.OfflineIM
private static ILogger m_logger;
private string m_ServerURI = string.Empty;
private IServiceAuth m_Auth;
private IServiceAuth? m_Auth;
private object m_Lock = new object();
public OfflineIMServiceRemoteConnector(string url)
@ -64,7 +62,7 @@ namespace OpenSim.OfflineIM
var cnf = config.GetSection("Messaging");
if (cnf.Exists() is false)
{
m_log.WarnFormat("[OfflineIM.V2.RemoteConnector]: Missing Messaging configuration");
m_logger.LogWarning("[OfflineIM.V2.RemoteConnector]: Missing Messaging configuration");
return;
}

View file

@ -40,7 +40,7 @@ using Microsoft.Extensions.Logging;
namespace OpenSim.OfflineIM
{
public class OfflineIMServiceRobustConnector : ServiceConnector, IServiceConnector
public class OfflineIMServiceRobustConnector : IServiceConnector
{
private IOfflineIMService m_OfflineIMService;
private static string m_ConfigName = "Messaging";
@ -48,6 +48,10 @@ namespace OpenSim.OfflineIM
private readonly IConfiguration m_configuration;
private readonly ILogger<OfflineIMServiceRobustConnector> m_logger;
public string ConfigName => m_ConfigName;
public IHttpServer HttpServer => throw new NotImplementedException();
public OfflineIMServiceRobustConnector(
IConfiguration configuration,
ILogger<OfflineIMServiceRobustConnector> logger,
@ -60,8 +64,7 @@ namespace OpenSim.OfflineIM
IConfiguration configuration,
ILogger<OfflineIMServiceRobustConnector> logger,
IHttpServer server,
string configName) :
base(configuration, server, configName)
string configName)
{
m_configuration = configuration;
m_logger = logger;
@ -74,6 +77,11 @@ namespace OpenSim.OfflineIM
server.AddStreamHandler(new OfflineIMServicePostHandler(m_OfflineIMService, auth));
}
public void Initialize(IHttpServer httpServer)
{
throw new NotImplementedException();
}
}
public class OfflineIMServicePostHandler : BaseStreamHandler
@ -195,8 +203,7 @@ namespace OpenSim.OfflineIM
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
doc.AppendChild(xmlnode);

View file

@ -35,6 +35,7 @@ using System.Timers;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
@ -42,7 +43,7 @@ using OpenSim.Services.Interfaces;
namespace OpenSim.OfflineIM
{
public class OfflineIMService : OfflineIMServiceBase, IOfflineIMService
public class OfflineIMService : IOfflineIMService
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const int MAX_IM = 25;
@ -50,10 +51,22 @@ namespace OpenSim.OfflineIM
private XmlSerializer m_serializer;
private static bool m_Initialized = false;
public OfflineIMService(IConfiguration config)
: base(config)
private readonly IConfiguration m_config;
private readonly ILogger m_logger;
private readonly IOfflineIMData m_Database;
public OfflineIMService(
IConfiguration config,
ILogger<OfflineIMService> logger,
IOfflineIMData offlineIMData
)
{
m_config = config;
m_logger = logger;
m_Database = offlineIMData;
m_serializer = new XmlSerializer(typeof(GridInstantMessage));
if (!m_Initialized)
{
m_Database.DeleteOld();

View file

@ -1,77 +0,0 @@
/*
* 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 Microsoft.Extensions.Configuration;
using OpenSim.Data;
namespace OpenSim.OfflineIM
{
public class OfflineIMServiceBase
{
protected IOfflineIMData m_Database = null;
public OfflineIMServiceBase(IConfiguration config)
{
string dllName = String.Empty;
string connString = String.Empty;
string realm = "im_offline";
//
// Try reading the [DatabaseService] section, if it exists
//
var dbConfig = config.GetSection("DatabaseService");
if (dbConfig.Exists())
{
if (dllName.Length == 0)
dllName = dbConfig.GetValue("StorageProvider", String.Empty);
if (connString.Length == 0)
connString = dbConfig.GetValue("ConnectionString", String.Empty);
}
//
// [Messaging] section overrides [DatabaseService], if it exists
//
var imConfig = config.GetSection("Messaging");
if (imConfig.Exists())
{
dllName = imConfig.GetValue("StorageProvider", dllName);
connString = imConfig.GetValue("ConnectionString", connString);
realm = imConfig.GetValue("Realm", realm);
}
//
// We tried, but this doesn't exist. We can't proceed.
//
if (string.IsNullOrEmpty(dllName))
throw new Exception("No StorageProvider configured");
m_Database = LoadPlugin<IOfflineIMData>(dllName, new Object[] { connString, realm });
if (m_Database == null)
throw new Exception("Could not find a storage interface in the given module " + dllName);
}
}
}

View file

@ -86,7 +86,7 @@ namespace OpenSim.Capabilities.Handlers
ExpiringKey<UUID> m_badRequests = new ExpiringKey<UUID>(30000);
FetchInvDescHandler webFetchHandler = new FetchInvDescHandler(m_InventoryService, m_LibraryService, null);
FetchInvDescHandler webFetchHandler = new FetchInvDescHandler(m_logger, m_InventoryService, m_LibraryService, null);
ISimpleStreamHandler reqHandler
= new SimpleStreamHandler("/CAPS/WebFetchInvDesc/", delegate(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{

View file

@ -446,6 +446,8 @@ public partial class OpenSimCoreContext : DbContext
{
entity.HasKey(e => e.Id).HasName("PRIMARY");
entity.HasIndex(e => e.AccessTime, "idx_fsassets_access_time");
entity
.ToTable("fsassets")
.HasCharSet("utf8mb3")

View file

@ -1,62 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AssemblyTitle>OpenSim.Data.PGSQL</AssemblyTitle>
<Company>http://opensimulator.org</Company>
<Product>OpenSim.Data.PGSQL</Product>
<Copyright>Copyright (c) OpenSimulator.org Developers 2007-2009</Copyright>
</PropertyGroup>
<ItemGroup>
<Reference Include="Npgsql">
<HintPath>..\..\bin\Npgsql.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="OpenMetaverse">
<HintPath>..\..\bin\OpenMetaverse.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="OpenMetaverse.StructuredData">
<HintPath>..\..\bin\OpenMetaverse.StructuredData.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="OpenMetaverseTypes">
<HintPath>..\..\bin\OpenMetaverseTypes.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Source\OpenSim.Data\OpenSim.Data.csproj" />
<ProjectReference Include="..\..\Source\OpenSim.Framework\OpenSim.Framework.csproj" />
<ProjectReference Include="..\..\Source\OpenSim.Framework.Console\OpenSim.Framework.Console.csproj" />
<ProjectReference Include="..\..\Source\OpenSim.Region.Framework\OpenSim.Region.Framework.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\AgentPrefs.migrations" />
<EmbeddedResource Include="Resources\AssetStore.migrations" />
<EmbeddedResource Include="Resources\AuthStore.migrations" />
<EmbeddedResource Include="Resources\Avatar.migrations" />
<EmbeddedResource Include="Resources\EstateStore.migrations" />
<EmbeddedResource Include="Resources\FriendsStore.migrations" />
<EmbeddedResource Include="Resources\FSAssetStore.migrations" />
<EmbeddedResource Include="Resources\GridStore.migrations" />
<EmbeddedResource Include="Resources\GridUserStore.migrations" />
<EmbeddedResource Include="Resources\HGTravelStore.migrations" />
<EmbeddedResource Include="Resources\IM_Store.migrations" />
<EmbeddedResource Include="Resources\InventoryStore.migrations" />
<EmbeddedResource Include="Resources\LogStore.migrations" />
<EmbeddedResource Include="Resources\os_groups_Store.migrations" />
<EmbeddedResource Include="Resources\Presence.migrations" />
<EmbeddedResource Include="Resources\RegionStore.migrations" />
<EmbeddedResource Include="Resources\UserAccount.migrations" />
<EmbeddedResource Include="Resources\UserProfiles.migrations" />
<EmbeddedResource Include="Resources\UserStore.migrations" />
<EmbeddedResource Include="Resources\XAssetStore.migrations" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="8.0.0" />
<PackageReference Include="RawScape.Nini" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
</Project>

View file

@ -1,62 +0,0 @@
/*
* 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
{
public class PGSQLAgentPreferencesData : IAgentPreferencesData
{
protected PGSQLGenericTableHandler<AgentPreferencesData> tableHandler = null;
public void Initialize(string connectionString, string realm) {
tableHandler = new();
tableHandler.Initialize(connectionString, realm, "AgentPrefs");
}
public AgentPreferencesData GetPrefs(UUID agentID)
{
AgentPreferencesData[] ret = Get("PrincipalID", agentID.ToString());
if (ret.Length == 0)
return null;
return ret[0];
}
public bool Store(AgentPreferencesData data) {
return tableHandler.Store(data);
}
}
}

View file

@ -1,322 +0,0 @@
/*
* 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 Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenMetaverse;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A PGSQL Interface for the Asset server
/// </summary>
public class PGSQLAssetData : AssetDataBase
{
private const string _migrationStore = "AssetStore";
private static ILogger m_logger;
private long m_ticksToEpoch;
/// <summary>
/// Database manager
/// </summary>
private PGSQLManager m_database;
private string m_connectionString;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
#region IPlugin Members
override public void Dispose() { }
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
// [Obsolete("Cannot be default-initialized!")]
override public void Initialise()
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<PGSQLAssetData>>();
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// Initialises asset interface
/// </summary>
/// <para>
/// a string instead of file, if someone writes the support
/// </para>
/// <param name="connectionString">connect string</param>
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);
}
/// <summary>
/// Database provider version.
/// </summary>
override public string Version
{
get { return m_database.getVersion(); }
}
/// <summary>
/// The name of this DB provider.
/// </summary>
override public string Name
{
get { return "PGSQL Asset storage engine"; }
}
#endregion
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset from m_database
/// </summary>
/// <param name="assetID">the asset UUID</param>
/// <returns></returns>
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");
}
}
}
/// <summary>
/// Create asset in m_database
/// </summary>
/// <param name="asset">the asset</param>
override public bool 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 > AssetBase.MAX_ASSET_NAME)
{
assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
m_logger.LogWarning(
"[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 > AssetBase.MAX_ASSET_DESC)
{
assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
m_logger.LogWarning(
"[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_logger.LogError("[ASSET DB]: Error storing item :" + e.Message + " sql "+sql);
}
}
return true;
}
// 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());
// }
// }
// }
/// <summary>
/// Check if the assets exist in the database.
/// </summary>
/// <param name="uuids">The assets' IDs</param>
/// <returns>For each asset: true if it exists, false otherwise</returns>
public override bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return new bool[0];
HashSet<UUID> exist = new HashSet<UUID>();
string ids = "'" + string.Join("','", uuids) + "'";
string sql = string.Format("SELECT id FROM assets WHERE id IN ({0})", ids);
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
UUID id = DBGuid.FromDB(reader["id"]);
exist.Add(id);
}
}
}
bool[] results = new bool[uuids.Length];
for (int i = 0; i < uuids.Length; i++)
results[i] = exist.Contains(uuids[i]);
return results;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(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
}
}

View file

@ -1,254 +0,0 @@
/*
* 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<string> 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 void Initialize(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, object>();
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<string>();
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<string, object> oAuth = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> oDado in data.Data)
{
if (oDado.Key != oDado.Key.ToLower())
{
oAuth.Add(oDado.Key.ToLower(), oDado.Value);
}
}
foreach (KeyValuePair<string, object> oDado in data.Data)
{
if (!oAuth.ContainsKey(oDado.Key.ToLower())) {
oAuth.Add(oDado.Key.ToLower(), oDado.Value);
}
}
*/
string[] fields = new List<string>(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;
}
}
}

View file

@ -1,73 +0,0 @@
/*
* 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 Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenSim.Server.Base;
using OpenMetaverse;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A PGSQL Interface for Avatar Storage
/// </summary>
public class PGSQLAvatarData : PGSQLGenericTableHandler<AvatarBaseData>,
IAvatarData
{
private ILogger m_logger;
public void Initialize(string connectionString, string realm)
{
m_logger = OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<PGSQLAvatarData>>();
base.Initialize(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;
}
}
}
}

View file

@ -1,612 +0,0 @@
/*
* 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.Data;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenMetaverse;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
public class PGSQLEstateStore : IEstateDataStore
{
private const string _migrationStore = "EstateStore";
private static ILogger m_logger;
private PGSQLManager _Database;
private string m_connectionString;
private FieldInfo[] _Fields;
private Dictionary<string, FieldInfo> _FieldMap = new Dictionary<string, FieldInfo>();
#region Public methods
public void Initialize(string connectionString)
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<PGSQLEstateStore>>();
Initialise(connectionString);
}
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
/// <summary>
/// Initialises the estatedata class.
/// </summary>
/// <param name="connectionString">connectionString.</param>
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;
}
}
/// <summary>
/// Loads the estate settings.
/// </summary>
/// <param name="regionID">region ID.</param>
/// <returns></returns>
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(int estateID)
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
es.EstateID = Convert.ToUInt32(estateID);
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<string> names = new List<string>(FieldList);
// Remove EstateID and use AutoIncrement
if (es.EstateID < 100)
names.Remove("EstateID");
string sql = string.Format("insert into estate_settings (\"{0}\") values ( :{1} )", String.Join("\",\"", names.ToArray()), String.Join(", :", names.ToArray()));
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand insertCommand = new NpgsqlCommand(sql, conn))
{
insertCommand.CommandText = sql;
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();
if (insertCommand.ExecuteNonQuery() > 0 && es.EstateID < 100)
{
// Only get Auto ID if we actually used it
insertCommand.CommandText = "Select cast(lastval() as int) as ID ;";
using (NpgsqlDataReader result = insertCommand.ExecuteReader())
{
if (result.Read())
{
es.EstateID = (uint)result.GetInt32(0);
}
}
}
}
//TODO check if this is needed??
es.Save();
}
/// <summary>
/// Stores the estate settings.
/// </summary>
/// <param name="es">estate settings</param>
public void StoreEstateSettings(EstateSettings es)
{
List<string> names = new List<string>(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<string>(_FieldMap.Keys).ToArray(); }
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
string sql = "select * 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.BanningUserID = new UUID((Guid)reader["banningUUID"]); //uuid;
eb.BanTime = Convert.ToInt32(reader["banTime"]);
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
}
}
}
private UUID[] LoadUUIDList(uint estateID, string table)
{
List<UUID> uuids = new List<UUID>();
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\", \"banningUUID\",\"banTime\" ) values ( :EstateID, :bannedUUID, '','','', :banningUUID, :banTime )";
cmd.Parameters.AddWithValue("bannedUUID", Guid.Empty);
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters["EstateID"].Value = b.EstateID;
cmd.Parameters["bannedUUID"].Value = b.BannedUserID.Guid;
cmd.Parameters["banningUUID"].Value = b.BanningUserID.Guid;
cmd.Parameters["banTime"].Value = b.BanTime;
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<EstateSettings> LoadEstateSettingsAll()
{
List<EstateSettings> allEstateSettings = new List<EstateSettings>();
List<int> allEstateIds = GetEstatesAll();
foreach (int estateId in allEstateIds)
allEstateSettings.Add(LoadEstateSettings(estateId));
return allEstateSettings;
}
public List<int> GetEstates(string search)
{
List<int> result = new List<int>();
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<int> GetEstatesAll()
{
List<int> result = new List<int>();
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<int> GetEstatesByOwner(UUID ownerID)
{
List<int> result = new List<int>();
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_logger.LogError("[REGION DB]: LinkRegion failed: " + ex.Message);
transaction.Rollback();
}
}
return false;
}
public List<UUID> GetRegions(int estateID)
{
List<UUID> result = new List<UUID>();
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
}
}

View file

@ -1,79 +0,0 @@
/*
* 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 Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Npgsql;
using OpenSim.Server.Base;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A database interface class to a user profile storage system
/// </summary>
public class PGSqlFramework
{
private static ILogger m_logger;
protected string m_connectionString;
protected object m_dbLock = new object();
protected void Initialize(string connectionString)
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<PGSqlFramework>>();
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_logger.LogError(e.Message, e);
return 0;
}
}
}
}
}
}

View file

@ -1,117 +0,0 @@
/*
* 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<FriendsData>, IFriendsData
{
public void Initialize(string connectionString, string realm)
{
base.Initialize(connectionString, realm, "FriendsStore");
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, "FriendsStore");
m.Update();
}
}
public override 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);
}
}
}

View file

@ -1,581 +0,0 @@
/*
* 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.Data;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.Logging;
using OpenSim.Server.Base;
using OpenMetaverse;
using Npgsql;
using Microsoft.Extensions.DependencyInjection;
namespace OpenSim.Data.PGSQL
{
public class PGSQLGenericTableHandler<T> : PGSqlFramework where T : class, new()
{
private static ILogger m_logger;
protected string? m_ConnectionString;
protected PGSQLManager? m_database; //used for parameter type translation
protected Dictionary<string, FieldInfo> m_Fields = new Dictionary<string, FieldInfo>();
protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>();
protected List<string> m_ColumnNames = null;
protected string? m_Realm = null;
protected FieldInfo m_DataField = null;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public void Initialize(string connectionString, string realm, string storeName)
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<PGSQLGenericTableHandler<T>>>();
base.Initialize(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, string>();
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<string>();
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<string> GetConstraints()
{
List<string> constraints = new List<string>();
string query = string.Format(@"select
a.attname as column_name
from
pg_class t,
pg_class i,
pg_index ix,
pg_attribute a
where
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and a.attrelid = t.oid
and a.attnum = ANY(ix.indkey)
and t.relkind = 'r'
and ix.indisunique = true
and t.relname = 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
constraints.Add((string)rdr[0]);
}
}
return constraints;
}
}
public virtual T[] Get(string field, string key)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
if ( m_FieldTypes.ContainsKey(field) )
cmd.Parameters.Add(m_database.CreateParameter(field, key, m_FieldTypes[field]));
else
cmd.Parameters.Add(m_database.CreateParameter(field, key));
string query = String.Format("SELECT * FROM {0} WHERE \"{1}\" = :{1}", m_Realm, field, field);
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
return DoQuery(cmd);
}
}
public virtual T[] Get(string field, string[] keys)
{
int flen = keys.Length;
if(flen == 0)
return new T[0];
int flast = flen - 1;
StringBuilder sb = new StringBuilder(1024);
sb.AppendFormat("select * from {0} where {1} IN ('", m_Realm, field);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
for (int i = 0 ; i < flen ; i++)
{
sb.Append(keys[i]);
if(i < flast)
sb.Append("','");
else
sb.Append("')");
}
string query = sb.ToString();
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
return DoQuery(cmd);
}
}
public virtual T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
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<T> result = new List<T>();
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<string, string> data =
new Dictionary<string, string>();
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 T[] Get(string where, NpgsqlParameter parameter)
{
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);
cmd.Parameters.Add(parameter);
conn.Open();
return DoQuery(cmd);
}
}
public virtual bool Store(T row)
{
List<string> constraintFields = GetConstraints();
List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>();
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
StringBuilder query = new StringBuilder();
List<String> names = new List<String>();
List<String> values = new List<String>();
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<string, string>(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<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key))
{
constraints.Add(new KeyValuePair<string, string>(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<string> terms = new List<string>();
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<string> terms = new List<string>();
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<string> terms = new List<string>();
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();
}
}
}
}

View file

@ -1,58 +0,0 @@
/*
* 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.
*/
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A PGSQL Interface for Avatar Storage
/// </summary>
public class PGSQLGridUserData : PGSQLGenericTableHandler<GridUserData>, IGridUserData
{
// private static readonly ILogger m_logger
public void Initialize(string connectionString, string realm)
{
base.Initialize(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));
}
}
}

View file

@ -1,482 +0,0 @@
/*
* 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 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 = "1";
return m_Groups.Get(pattern);
}
else
{
pattern = " \"ShowInList\" = 1 AND lower(\"Name\") LIKE lower('%" + pattern + "%')";
return m_Groups.Get(pattern, new NpgsqlParameter("pattern", 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<GroupData>
{
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<MembershipData>
{
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<RoleData>
{
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<RoleMembershipData>
{
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<InvitationData>
{
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()
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.CommandText = String.Format("delete from {0} where \"TMStamp\"::abstime::timestamp < now() - INTERVAL '2 week'", m_Realm);
ExecuteNonQuery(cmd);
}
}
}
public class PGSqlGroupsNoticesHandler : PGSQLGenericTableHandler<NoticeData>
{
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()
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.CommandText = String.Format("delete from {0} where \"TMStamp\"::abstime::timestamp < now() - INTERVAL '2 week'", m_Realm);
ExecuteNonQuery(cmd);
}
}
}
public class PGSqlGroupsPrincipalsHandler : PGSQLGenericTableHandler<PrincipalData>
{
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)
{
}
}
}

View file

@ -1,76 +0,0 @@
/*
* 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 OpenMetaverse;
using Npgsql;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A PGSQL Interface for user grid data
/// </summary>
public class PGSQLHGTravelData : PGSQLGenericTableHandler<HGTravelingData>, IHGTravelingData
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public void Initialize(string connectionString, string realm) {
base.Initialize(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);
}
}
}
}

View file

@ -1,836 +0,0 @@
/*
* 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.Data;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenMetaverse;
using Npgsql;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A PGSQL interface for the inventory server
/// </summary>
public class PGSQLInventoryData : IInventoryDataPlugin
{
private const string _migrationStore = "InventoryStore";
private static ILogger m_logger;
/// <summary>
/// The database manager
/// </summary>
private PGSQLManager database;
private string m_connectionString;
#region IPlugin members
[Obsolete("Cannot be default-initialized!")]
public void Initialise()
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<PGSQLInventoryData>>();
m_logger.LogInformation("[PGSQLInventoryData]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// Loads and initialises the PGSQL inventory storage interface
/// </summary>
/// <param name="connectionString">connect string</param>
/// <remarks>use PGSQL_connection.ini</remarks>
public void Initialise(string connectionString)
{
m_connectionString = connectionString;
database = new PGSQLManager(connectionString);
//New migrations check of store
database.CheckMigration(_migrationStore);
}
/// <summary>
/// The name of this DB provider
/// </summary>
/// <returns>A string containing the name of the DB provider</returns>
public string Name
{
get { return "PGSQL Inventory Data Interface"; }
}
/// <summary>
/// Closes this DB provider
/// </summary>
public void Dispose()
{
database = null;
}
/// <summary>
/// Returns the version of this DB provider
/// </summary>
/// <returns>A string containing the DB provider</returns>
public string Version
{
get { return database.getVersion(); }
}
#endregion
#region Folder methods
/// <summary>
/// Returns a list of the root folders within a users inventory
/// </summary>
/// <param name="user">The user whos inventory is to be searched</param>
/// <returns>A list of folder objects</returns>
public List<InventoryFolderBase> getUserRootFolders(UUID user)
{
if (user.IsZero())
return new List<InventoryFolderBase>();
return getInventoryFolders(UUID.Zero, user);
}
/// <summary>
/// see InventoryItemBase.getUserRootFolder
/// </summary>
/// <param name="user">the User UUID</param>
/// <returns></returns>
public InventoryFolderBase getUserRootFolder(UUID user)
{
List<InventoryFolderBase> 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;
}
/// <summary>
/// Returns a list of folders in a users inventory contained within the specified folder
/// </summary>
/// <param name="parentID">The folder to search</param>
/// <returns>A list of inventory folders</returns>
public List<InventoryFolderBase> getInventoryFolders(UUID parentID)
{
return getInventoryFolders(parentID, UUID.Zero);
}
/// <summary>
/// Returns a specified inventory folder
/// </summary>
/// <param name="folderID">The folder to return</param>
/// <returns>A folder class</returns>
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_logger.LogInformation("[INVENTORY DB] : Found no inventory folder with ID : {0}", folderID);
return null;
}
/// <summary>
/// Returns all child folders in the hierarchy from the parent folder and down.
/// Does not return the parent folder itself.
/// </summary>
/// <param name="parentID">The folder to get subfolders for</param>
/// <returns>A list of inventory folders</returns>
public List<InventoryFolderBase> 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<InventoryFolderBase> folders = new List<InventoryFolderBase>();
if (parentID.IsZero())
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<InventoryFolderBase> tempFolders = new List<InventoryFolderBase>();
foreach (InventoryFolderBase folderBase in folders)
{
tempFolders.AddRange(getFolderHierarchy(folderBase.ID, cmd));
}
if (tempFolders.Count > 0)
{
folders.AddRange(tempFolders);
}
}
return folders;
}
/// <summary>
/// Creates a new inventory folder
/// </summary>
/// <param name="folder">Folder to create</param>
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_logger.LogWarning("[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_logger.LogError("[INVENTORY DB]: Error : {0}", e.Message);
}
}
}
/// <summary>
/// Updates an inventory folder
/// </summary>
/// <param name="folder">Folder to update</param>
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_logger.LogWarning("[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_logger.LogError("[INVENTORY DB]: Error : {0}", e.Message);
}
}
}
/// <summary>
/// Updates an inventory folder
/// </summary>
/// <param name="folder">Folder to update</param>
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_logger.LogError("[INVENTORY DB]: Error : {0}", e.Message);
}
}
}
/// <summary>
/// Delete an inventory folder
/// </summary>
/// <param name="folderID">Id of folder to delete</param>
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<InventoryFolderBase> 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
/// <summary>
/// Returns a list of items in a specified folder
/// </summary>
/// <param name="folderID">The folder to search</param>
/// <returns>A list containing inventory items</returns>
public List<InventoryItemBase> 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<InventoryItemBase> items = new List<InventoryItemBase>();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
items.Add(readInventoryItem(reader));
}
}
return items;
}
}
/// <summary>
/// Returns a specified inventory item
/// </summary>
/// <param name="itemID">The item ID</param>
/// <returns>An inventory item</returns>
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_logger.LogInformation("[INVENTORY DB]: Found no inventory item with ID : {0}", itemID);
return null;
}
/// <summary>
/// Adds a specified item to the database
/// </summary>
/// <param name="item">The inventory item</param>
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_logger.LogWarning("[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_logger.LogWarning("[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_logger.LogError("[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_logger.LogError("[INVENTORY DB] Error updating inventory folder for new item :" + e.Message);
}
}
}
/// <summary>
/// Updates the specified inventory item
/// </summary>
/// <param name="item">Inventory item to update</param>
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_logger.LogWarning("[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_logger.LogWarning("[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_logger.LogError("[INVENTORY DB]: Error updating item :" + e.Message);
}
}
}
// See IInventoryDataPlugin
/// <summary>
/// Delete an item in inventory database
/// </summary>
/// <param name="itemID">the item UUID</param>
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_logger.LogError("[INVENTORY DB]: Error deleting item :" + e.Message);
}
}
}
public InventoryItemBase queryInventoryItem(UUID itemID)
{
return getInventoryItem(itemID);
}
public InventoryFolderBase queryInventoryFolder(UUID folderID)
{
return getInventoryFolder(folderID);
}
/// <summary>
/// Returns all activated gesture-items in the inventory of the specified avatar.
/// </summary>
/// <param name="avatarID">The <see cref="UUID"/> of the avatar</param>
/// <returns>
/// The list of gestures (<see cref="InventoryItemBase"/>s)
/// </returns>
public List<InventoryItemBase> 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<InventoryItemBase> gestureList = new List<InventoryItemBase>();
while (reader.Read())
{
gestureList.Add(readInventoryItem(reader));
}
return gestureList;
}
}
}
#endregion
#region Private methods
/// <summary>
/// Delete an item in inventory database
/// </summary>
/// <param name="folderID">the item ID</param>
/// <param name="connection">connection to the database</param>
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_logger.LogError("[INVENTORY DB] Error deleting item :" + e.Message);
}
}
}
/// <summary>
/// Gets the folder hierarchy in a loop.
/// </summary>
/// <param name="parentID">parent ID.</param>
/// <param name="command">SQL command/connection to database</param>
/// <returns></returns>
private static List<InventoryFolderBase> getFolderHierarchy(UUID parentID, NpgsqlCommand command)
{
command.Parameters["parentID"].Value = parentID.Guid; //.ToString();
List<InventoryFolderBase> folders = getInventoryFolders(command);
if (folders.Count > 0)
{
List<InventoryFolderBase> tempFolders = new List<InventoryFolderBase>();
foreach (InventoryFolderBase folderBase in folders)
{
tempFolders.AddRange(getFolderHierarchy(folderBase.ID, command));
}
if (tempFolders.Count > 0)
{
folders.AddRange(tempFolders);
}
}
return folders;
}
/// <summary>
/// Gets the inventory folders.
/// </summary>
/// <param name="parentID">parentID, use UUID.Zero to get root</param>
/// <param name="user">user id, use UUID.Zero, if you want all folders from a parentID.</param>
/// <returns></returns>
private List<InventoryFolderBase> 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.IsZero())
{
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);
}
}
/// <summary>
/// Gets the inventory folders.
/// </summary>
/// <param name="command">SQLcommand.</param>
/// <returns></returns>
private static List<InventoryFolderBase> getInventoryFolders(NpgsqlCommand command)
{
using (NpgsqlDataReader reader = command.ExecuteReader())
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
{
items.Add(readInventoryFolder(reader));
}
return items;
}
}
/// <summary>
/// Reads a list of inventory folders returned by a query.
/// </summary>
/// <param name="reader">A PGSQL Data Reader</param>
/// <returns>A List containing inventory folders</returns>
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_logger.LogError("[INVENTORY DB] Error reading inventory folder :" + e.Message);
}
return null;
}
/// <summary>
/// Reads a one item from an SQL result
/// </summary>
/// <param name="reader">The SQL Result</param>
/// <returns>the item read</returns>
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_logger.LogError("[INVENTORY DB]: Error reading inventory item :" + e.Message);
}
return null;
}
/// <summary>
/// Delete a folder in inventory databasae
/// </summary>
/// <param name="folderID">the folder UUID</param>
/// <param name="connection">connection to database</param>
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_logger.LogError("[INVENTORY DB]: Error deleting folder :" + e.Message);
}
}
#endregion
}
}

View file

@ -1,323 +0,0 @@
/*
* 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.Data;
using System.Reflection;
using OpenMetaverse;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A management class for the MS SQL Storage Engine
/// </summary>
public class PGSQLManager
{
//private static readonly ILogger m_logger;
/// <summary>
/// Connection string for ADO.net
/// </summary>
private readonly string connectionString;
/// <summary>
/// Initialize the manager and set the connectionstring
/// </summary>
/// <param name="connection"></param>
public PGSQLManager(string connection)
{
connectionString = connection;
}
/// <summary>
/// Type conversion to a SQLDbType functions
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
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.Length == 0)
{
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);
}
/// <summary>
/// Creates value for parameter.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
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;
}
/// <summary>
/// Create value for parameter based on PGSQL Schema
/// </summary>
/// <param name="value"></param>
/// <param name="PGFieldType"></param>
/// <returns></returns>
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;
}
if (PGFieldType == "double precision")
{
return Convert.ToDouble(value);
}
return CreateParameterValue(value);
}
/// <summary>
/// Create a parameter for a command
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <param name="parameterObject">parameter object.</param>
/// <returns></returns>
internal NpgsqlParameter CreateParameter(string parameterName, object parameterObject)
{
return CreateParameter(parameterName, parameterObject, false);
}
/// <summary>
/// Creates the parameter for a command.
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <param name="parameterObject">parameter object.</param>
/// <param name="parameterOut">if set to <c>true</c> parameter is a output parameter</param>
/// <returns></returns>
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;
}
/// <summary>
/// Create a parameter with PGSQL schema type
/// </summary>
/// <param name="parameterName"></param>
/// <param name="parameterObject"></param>
/// <param name="PGFieldType"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Checks if we need to do some migrations to the database
/// </summary>
/// <param name="migrationStore">migrationStore.</param>
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();
}
}
/// <summary>
/// Returns the version of this DB provider
/// </summary>
/// <returns>A string containing the DB provider</returns>
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);
}
}
}

View file

@ -1,102 +0,0 @@
/*
* 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);
}
}
}
}
}

View file

@ -1,56 +0,0 @@
/*
* 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<OfflineIMData>, 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);
}
}
}
}

View file

@ -1,110 +0,0 @@
/*
* 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 OpenMetaverse;
using Npgsql;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A PGSQL Interface for the Presence Server
/// </summary>
public class PGSQLPresenceData : PGSQLGenericTableHandler<PresenceData>,
IPresenceData
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public void Initialize(string connectionString, string realm)
{
base.Initialize(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;
if (regionID.IsZero())
return false;
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.CommandText = String.Format("UPDATE {0} SET \"RegionID\" = :regionID, \"LastSeen\" = now() 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;
}
}
}

View file

@ -1,459 +0,0 @@
/*
* 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.Data;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenSim.Framework;
using RegionFlags = OpenSim.Framework.RegionFlags;
using OpenSim.Server.Base;
using OpenMetaverse;
using Npgsql;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A PGSQL Interface for the Region Server.
/// </summary>
public class PGSQLRegionData : IRegionData
{
private static ILogger m_logger;
private string m_Realm;
private List<string> m_ColumnNames = null;
private string m_ConnectionString;
private PGSQLManager m_database;
protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>();
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public void Initialize(string connectionString, string realm)
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<PGSQLRegionData>>();
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, string>();
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<RegionData> Get(string regionName, UUID scopeID)
{
string sql = "select * from "+m_Realm+" where lower(\"regionName\") like lower(:regionName) ";
if (!scopeID.IsZero())
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.IsZero())
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
return RunCommand(cmd);
}
}
public RegionData GetSpecific(string regionName, UUID scopeID)
{
string sql = "select * from " + m_Realm + " where lower(\"regionName\") = lower(:regionName) ";
if (!scopeID.IsZero())
sql += " and \"ScopeID\" = :scopeID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("regionName", regionName));
if (!scopeID.IsZero())
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
}
}
public RegionData Get(int posX, int posY, UUID scopeID)
{
// extend database search for maximum region size area
string sql = "select * from "+m_Realm+" where \"locX\" between :startX and :endX and \"locY\" between :startY and :endY";
if (!scopeID.IsZero())
sql += " and \"ScopeID\" = :scopeID";
int startX = posX - (int)Constants.MaximumRegionSize;
int startY = posY - (int)Constants.MaximumRegionSize;
int endX = posX;
int endY = posY;
List<RegionData> ret;
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));
if (!scopeID.IsZero())
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
ret = RunCommand(cmd);
}
if (ret.Count == 0)
return null;
// Find the first that contains pos
RegionData rg = null;
foreach (RegionData r in ret)
{
if (posX >= r.posX && posX < r.posX + r.sizeX
&& posY >= r.posY && posY < r.posY + r.sizeY)
{
rg = r;
break;
}
}
return rg;
}
public RegionData Get(UUID regionID, UUID scopeID)
{
string sql = "select * from "+m_Realm+" where uuid = :regionID";
if (!scopeID.IsZero())
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.IsZero())
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
}
}
public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID)
{
// extend database search for maximum region size area
string sql = "select * from "+m_Realm+" where \"locX\" between :startX and :endX and \"locY\" between :startY and :endY";
if (!scopeID.IsZero())
sql += " and \"ScopeID\" = :scopeID";
int qstartX = startX - (int)Constants.MaximumRegionSize;
int qstartY = startY - (int)Constants.MaximumRegionSize;
List<RegionData> dbret;
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("startX", qstartX));
cmd.Parameters.Add(m_database.CreateParameter("startY", qstartY));
cmd.Parameters.Add(m_database.CreateParameter("endX", endX));
cmd.Parameters.Add(m_database.CreateParameter("endY", endY));
if (!scopeID.IsZero())
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
dbret = RunCommand(cmd);
}
List<RegionData> ret = new List<RegionData>();
if(dbret.Count == 0)
return ret;
foreach (RegionData r in dbret)
{
if (r.posX + r.sizeX > startX && r.posX <= endX
&& r.posY + r.sizeY > startY && r.posY <= endY)
ret.Add(r);
}
return ret;
}
public List<RegionData> RunCommand(NpgsqlCommand cmd)
{
List<RegionData> retList = new List<RegionData>();
NpgsqlDataReader result = cmd.ExecuteReader();
while (result.Read())
{
RegionData ret = new RegionData();
ret.Data = new Dictionary<string, object>();
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<string>();
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<string>(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.IsZero())
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_logger.LogWarning("[PGSQL Grid]: Error inserting into Regions table: " + ex.Message + ", INSERT sql: " + insert);
}
}
}
catch (Exception ex)
{
m_logger.LogWarning("[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<RegionData> GetDefaultRegions(UUID scopeID)
{
return Get((int)RegionFlags.DefaultRegion, scopeID);
}
public List<RegionData> GetDefaultHypergridRegions(UUID scopeID)
{
return Get((int)RegionFlags.DefaultHGRegion, scopeID);
}
public List<RegionData> GetFallbackRegions(UUID scopeID)
{
return Get((int)RegionFlags.FallbackRegion, scopeID);
}
public List<RegionData> GetHyperlinks(UUID scopeID)
{
return Get((int)RegionFlags.Hyperlink, scopeID);
}
public List<RegionData> GetOnlineRegions(UUID scopeID)
{
return Get((int)RegionFlags.RegionOnline, scopeID);
}
private List<RegionData> Get(int regionFlags, UUID scopeID)
{
string sql = "SELECT * FROM " + m_Realm + " WHERE (\"flags\" & " + regionFlags.ToString() + ") <> 0";
if (!scopeID.IsZero())
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);
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,329 +0,0 @@
/*
* 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 OpenMetaverse;
using Npgsql;
namespace OpenSim.Data.PGSQL
{
public class PGSQLUserAccountData : PGSQLGenericTableHandler<UserAccountData>,IUserAccountData
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public void Initialize(string connectionString, string realm)
{
base.Initialize(connectionString, realm, "UserAccount");
}
/*
private string m_Realm;
private List<string> 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<UserAccountData> 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<string, string> data = retUA[0].Data;
Dictionary<string, string> data2 = new Dictionary<string, string>();
foreach (KeyValuePair<string,string> 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<string, string> 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, string>();
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<string>();
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<string>(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();
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 = "";
UUID scope_id;
UUID.TryParse(scopeID.ToString(), out scope_id);
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""=:UUIDZero) and (""FirstName"" ilike :search or ""LastName"" ilike :search)", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("scopeID", (UUID)scope_id));
cmd.Parameters.Add (m_database.CreateParameter("UUIDZero", (UUID)UUID.Zero));
cmd.Parameters.Add(m_database.CreateParameter("search", "%" + words[0] + "%"));
}
else
{
sql = String.Format(@"select * from {0} where (""ScopeID""=:ScopeID or ""ScopeID""=:UUIDZero) 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("UUIDZero", (UUID)UUID.Zero));
cmd.Parameters.Add(m_database.CreateParameter("ScopeID", (UUID)scope_id));
}
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
return DoQuery(cmd);
}
}
public UserAccountData[] GetUsersWhere(UUID scopeID, string where)
{
return null;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,593 +0,0 @@
/*
* 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.Data;
using System.IO.Compression;
using System.Reflection;
using System.Security.Cryptography;
using OpenSim.Framework;
using OpenMetaverse;
using Npgsql;
using OpenSim.Server.Base;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace OpenSim.Data.PGSQL
{
public class PGSQLXAssetData : IXAssetDataPlugin
{
private static ILogger m_logger;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
/// <summary>
/// Number of days that must pass before we update the access time on an asset when it has been fetched.
/// </summary>
private const int DaysBetweenAccessTimeUpdates = 30;
private bool m_enableCompression = false;
private PGSQLManager m_database;
private string m_connectionString;
private object m_dbLock = new object();
/// <summary>
/// We can reuse this for all hashing since all methods are single-threaded through m_dbBLock
/// </summary>
private HashAlgorithm hasher = SHA256.Create();
#region IPlugin Members
public string Version { get { return "1.0.0.0"; } }
/// <summary>
/// <para>Initialises Asset interface</para>
/// <para>
/// <list type="bullet">
/// <item>Loads and initialises the PGSQL storage plugin.</item>
/// <item>Warns and uses the obsolete pgsql_connection.ini if connect string is empty.</item>
/// <item>Check for migration</item>
/// </list>
/// </para>
/// </summary>
/// <param name="connect">connect string</param>
public void Initialise(string connect)
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<PGSQLXAssetData>>();
m_logger.LogError("[PGSQL XASSETDATA]: ***********************************************************");
m_logger.LogError("[PGSQL XASSETDATA]: ***********************************************************");
m_logger.LogError("[PGSQL XASSETDATA]: ***********************************************************");
m_logger.LogError("[PGSQL XASSETDATA]: THIS PLUGIN IS STRICTLY EXPERIMENTAL.");
m_logger.LogError("[PGSQL XASSETDATA]: DO NOT USE FOR ANY DATA THAT YOU DO NOT MIND LOSING.");
m_logger.LogError("[PGSQL XASSETDATA]: DATABASE TABLES CAN CHANGE AT ANY TIME, CAUSING EXISTING DATA TO BE LOST.");
m_logger.LogError("[PGSQL XASSETDATA]: ***********************************************************");
m_logger.LogError("[PGSQL XASSETDATA]: ***********************************************************");
m_logger.LogError("[PGSQL XASSETDATA]: ***********************************************************");
m_connectionString = connect;
m_database = new PGSQLManager(m_connectionString);
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() { }
/// <summary>
/// The name of this DB provider
/// </summary>
public string Name
{
get { return "PGSQL XAsset storage engine"; }
}
#endregion
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset <paramref name="assetID"/> from database
/// </summary>
/// <param name="assetID">Asset UUID to fetch</param>
/// <returns>Return the asset</returns>
/// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks>
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, access_time, ""AssetType"", local, temporary, asset_flags, creatorid, data
FROM XAssetsMeta
JOIN XAssetsData ON XAssetsMeta.hash = XAssetsData.Hash WHERE id=:ID",
dbcon))
{
cmd.Parameters.Add(m_database.CreateParameter("ID", assetID));
try
{
using (NpgsqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
asset = new AssetBase(
assetID,
(string)dbReader["name"],
Convert.ToSByte(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["asset_flags"]);
if (m_enableCompression)
{
using(MemoryStream ms = new MemoryStream(asset.Data))
using(GZipStream decompressionStream = new GZipStream(ms, CompressionMode.Decompress))
{
using(MemoryStream outputStream = new MemoryStream())
{
decompressionStream.CopyTo(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["access_time"]);
}
}
}
catch (Exception e)
{
m_logger.LogError(string.Format("[PGSQL XASSET DATA]: Failure fetching asset {0}", assetID), e);
}
}
}
}
return asset;
}
/// <summary>
/// Create an asset in database, or update it if existing.
/// </summary>
/// <param name="asset">Asset UUID to create</param>
/// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks>
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_logger.LogWarning(
"[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_logger.LogWarning(
"[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);
UUID asset_id;
UUID.TryParse(asset.ID, out asset_id);
// 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, create_time, access_time, asset_flags, 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, create_time = :CreateTime,
access_time = :AccessTime, asset_flags = :AssetFlags, creatorid = :CreatorID
where id = :ID;
",
dbcon))
{
// create unix epoch time
int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
cmd.Parameters.Add(m_database.CreateParameter("ID", asset_id));
cmd.Parameters.Add(m_database.CreateParameter("Hash", hash));
cmd.Parameters.Add(m_database.CreateParameter("Name", assetName));
cmd.Parameters.Add(m_database.CreateParameter("Description", assetDescription));
cmd.Parameters.Add(m_database.CreateParameter("AssetType", asset.Type));
cmd.Parameters.Add(m_database.CreateParameter("Local", asset.Local));
cmd.Parameters.Add(m_database.CreateParameter("Temporary", asset.Temporary));
cmd.Parameters.Add(m_database.CreateParameter("CreateTime", now));
cmd.Parameters.Add(m_database.CreateParameter("AccessTime", now));
cmd.Parameters.Add(m_database.CreateParameter("CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(m_database.CreateParameter("AssetFlags", (int)asset.Flags));
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_logger.LogError("[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.Add(m_database.CreateParameter("Hash", hash));
cmd.Parameters.Add(m_database.CreateParameter("Data", asset.Data));
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_logger.LogError("[XASSET DB]: PGSQL failure creating asset data {0} with name \"{1}\". Error: {2}",
asset.FullID, asset.Name, e.Message);
transaction.Rollback();
return;
}
}
transaction.Commit();
}
}
}
}
/// <summary>
/// Updates the access time of the asset if it was accessed above a given threshhold amount of time.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name='asset'></param>
/// <param name='accessTime'></param>
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 access_time=:AccessTime where id=:ID", dbcon);
try
{
UUID asset_id;
UUID.TryParse(assetMetadata.ID, out asset_id);
using (cmd)
{
// create unix epoch time
cmd.Parameters.Add(m_database.CreateParameter("id", asset_id));
cmd.Parameters.Add(m_database.CreateParameter("access_time", (int)Utils.DateTimeToUnixTime(now)));
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_logger.LogError(
"[XASSET PGSQL DB]: Failure updating access_time for asset {0} with name {1} : {2}",
assetMetadata.ID, assetMetadata.Name, e.Message);
}
}
}
}
/// <summary>
/// We assume we already have the m_dbLock.
/// </summary>
/// TODO: need to actually use the transaction.
/// <param name="dbcon"></param>
/// <param name="transaction"></param>
/// <param name="hash"></param>
/// <returns></returns>
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.Add(m_database.CreateParameter("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_logger.LogError(
"[XASSETS DB]: PGSql failure in ExistsData fetching hash {0}. Exception {1}{2}",
hash, e.Message, e.StackTrace);
}
}
return exists;
}
/// <summary>
/// Check if the assets exist in the database.
/// </summary>
/// <param name="uuids">The assets' IDs</param>
/// <returns>For each asset: true if it exists, false otherwise</returns>
public bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return new bool[0];
HashSet<UUID> exist = new HashSet<UUID>();
string ids = "'" + string.Join("','", uuids) + "'";
string sql = string.Format(@"SELECT id FROM XAssetsMeta WHERE id IN ({0})", ids);
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
UUID id = DBGuid.FromDB(reader["id"]);
exist.Add(id);
}
}
}
}
bool[] results = new bool[uuids.Length];
for (int i = 0; i < uuids.Length; i++)
results[i] = exist.Contains(uuids[i]);
return results;
}
/// <summary>
/// Check if the asset exists in the database
/// </summary>
/// <param name="uuid">The asset UUID</param>
/// <returns>true if it exists, false otherwise.</returns>
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.Add(m_database.CreateParameter("id", uuid));
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_logger.LogError(string.Format("[XASSETS DB]: PGSql failure fetching asset {0}", uuid), e);
}
}
}
}
return assetExists;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
lock (m_dbLock)
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString))
{
dbcon.Open();
using(NpgsqlCommand cmd = new NpgsqlCommand(@"SELECT name, description, access_time, ""AssetType"", temporary, id, asset_flags, creatorid
FROM XAssetsMeta
LIMIT :start, :count",dbcon))
{
cmd.Parameters.Add(m_database.CreateParameter("start",start));
cmd.Parameters.Add(m_database.CreateParameter("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 = Convert.ToSByte(dbReader["AssetType"]);
metadata.Temporary = Convert.ToBoolean(dbReader["temporary"]);
metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]);
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["access_time"]);
retList.Add(metadata);
}
}
}
catch (Exception e)
{
m_logger.LogError("[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.Add(m_database.CreateParameter(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
}
}

View file

@ -1,341 +0,0 @@
/*
* 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 OpenMetaverse;
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)
{
this.Initialize(conn, realm);
}
public void Initialize(string connString, string realm) {
m_Folders = new PGSQLFolderHandler(
connString, "inventoryfolders", "InventoryStore");
m_Items = new PGSQLItemHandler(
connString, "inventoryitems", String.Empty);
}
public static UUID str2UUID(string strUUID)
{
UUID newUUID = UUID.Zero;
UUID.TryParse(strUUID, out newUUID);
return newUUID;
}
public XInventoryFolder[] GetFolder(string field, string val)
{
return m_Folders.Get(field, val);
}
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<XInventoryItem>
{
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);
cmd.CommandText = String.Format(@"select * from inventoryitems where ""avatarID"" = :uuid and ""assetType"" = :type and ""flags"" = 1");
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.CommandText = String.Format(@"select bit_or(""inventoryCurrentPermissions"") as ""inventoryCurrentPermissions""
from inventoryitems
where ""avatarID""::uuid = :PrincipalID
and ""assetID""::uuid = :AssetID
group by ""assetID"" ");
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<XInventoryFolder>
{
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<T> : PGSQLGenericTableHandler<T> 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;
}
}
}

View file

@ -1,19 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS "public"."agentprefs" (
"PrincipalID" uuid NOT NULL,
"AccessPrefs" char(2) NOT NULL DEFAULT 'M'::bpchar COLLATE "default",
"HoverHeight" float8 NOT NULL DEFAULT 0,
"Language" char(5) NOT NULL DEFAULT 'en-us'::bpchar COLLATE "default",
"LanguageIsPublic" bool NOT NULL DEFAULT true,
"PermEveryone" int4 NOT NULL DEFAULT 0,
"PermGroup" int4 NOT NULL DEFAULT 0,
"PermNextOwner" int4 NOT NULL DEFAULT 532480
)
WITH (OIDS=FALSE);
ALTER TABLE "public"."agentprefs" ADD PRIMARY KEY ("PrincipalID") NOT DEFERRABLE INITIALLY IMMEDIATE;
COMMIT;

View file

@ -1,110 +0,0 @@
: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 '';
:VERSION 8
BEGIN TRANSACTION;
COMMIT;
:VERSION 9
BEGIN TRANSACTION;
--# "creatorID" goes up to VARCHAR(128)
alter table assets
alter column "creatorID" type varchar(128);
Commit;

View file

@ -1,40 +0,0 @@
: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;
:VERSION 3
BEGIN TRANSACTION;
CREATE UNIQUE INDEX auth_pkey ON auth USING btree (uuid);
ALTER TABLE tokens ADD CONSTRAINT "uuid_token" UNIQUE ("uuid","token") NOT DEFERRABLE INITIALLY IMMEDIATE;
COMMIT;

View file

@ -1,59 +0,0 @@
: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;

View file

@ -1,141 +0,0 @@
:VERSION 12
BEGIN TRANSACTION;
-- ----------------------------
-- Table structure for estate_groups
-- ----------------------------
CREATE TABLE IF NOT EXISTS "public"."estate_groups" (
"EstateID" int4 NOT NULL,
"uuid" uuid NOT NULL
)
WITH (OIDS=FALSE);
-- Indexes structure for table estate_groups
-- ----------------------------
CREATE INDEX IF NOT EXISTS "ix_estate_groups" ON "public"."estate_groups" USING btree("EstateID" "pg_catalog"."int4_ops" ASC NULLS LAST);
-- ----------------------------
-- Table structure for estate_managers
-- ----------------------------
CREATE TABLE IF NOT EXISTS "public"."estate_managers" (
"EstateID" int4 NOT NULL,
"uuid" uuid NOT NULL
)
WITH (OIDS=FALSE);
-- Indexes structure for table estate_managers
-- ----------------------------
CREATE INDEX IF NOT EXISTS "ix_estate_managers" ON "public"."estate_managers" USING btree("EstateID" "pg_catalog"."int4_ops" ASC NULLS LAST);
-- ----------------------------
-- Table structure for estate_map
-- ----------------------------
CREATE TABLE IF NOT EXISTS "public"."estate_map" (
"RegionID" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
"EstateID" int4 NOT NULL
)
WITH (OIDS=FALSE);
-- Primary key structure for table estate_map
-- ----------------------------
ALTER TABLE "public"."estate_map" ADD PRIMARY KEY ("RegionID") NOT DEFERRABLE INITIALLY IMMEDIATE;
-- ----------------------------
-- Table structure for estate_settings
-- ----------------------------
CREATE TABLE IF NOT EXISTS "public"."estate_settings" (
"EstateID" int4 NOT NULL DEFAULT nextval('estate_settings_id'::regclass),
"EstateName" varchar(64) DEFAULT NULL::character varying COLLATE "default",
"AbuseEmailToEstateOwner" bool NOT NULL,
"DenyAnonymous" bool NOT NULL,
"ResetHomeOnTeleport" bool NOT NULL,
"FixedSun" bool NOT NULL,
"DenyTransacted" bool NOT NULL,
"BlockDwell" bool NOT NULL,
"DenyIdentified" bool NOT NULL,
"AllowVoice" bool NOT NULL,
"UseGlobalTime" bool NOT NULL,
"PricePerMeter" int4 NOT NULL,
"TaxFree" bool NOT NULL,
"AllowDirectTeleport" bool NOT NULL,
"RedirectGridX" int4 NOT NULL,
"RedirectGridY" int4 NOT NULL,
"ParentEstateID" int4 NOT NULL,
"SunPosition" float8 NOT NULL,
"EstateSkipScripts" bool NOT NULL,
"BillableFactor" float8 NOT NULL,
"PublicAccess" bool NOT NULL,
"AbuseEmail" varchar(255) NOT NULL COLLATE "default",
"EstateOwner" uuid NOT NULL,
"DenyMinors" bool NOT NULL,
"AllowLandmark" bool NOT NULL DEFAULT true,
"AllowParcelChanges" bool NOT NULL DEFAULT true,
"AllowSetHome" bool NOT NULL DEFAULT true
)
WITH (OIDS=FALSE);
-- Primary key structure for table estate_settings
-- ----------------------------
ALTER TABLE "public"."estate_settings" ADD PRIMARY KEY ("EstateID") NOT DEFERRABLE INITIALLY IMMEDIATE;
-- ----------------------------
-- Table structure for estate_users
-- ----------------------------
CREATE TABLE IF NOT EXISTS "public"."estate_users" (
"EstateID" int4 NOT NULL,
"uuid" uuid NOT NULL
)
WITH (OIDS=FALSE);
-- Indexes structure for table estate_users
-- ----------------------------
CREATE INDEX IF NOT EXISTS "ix_estate_users" ON "public"."estate_users" USING btree("EstateID" "pg_catalog"."int4_ops" ASC NULLS LAST);
-- ----------------------------
-- Table structure for estateban
-- ----------------------------
CREATE TABLE IF NOT EXISTS "public"."estateban" (
"EstateID" int4 NOT NULL,
"bannedUUID" uuid NOT NULL,
"bannedIp" varchar(16) COLLATE "default",
"bannedIpHostMask" varchar(16) COLLATE "default",
"bannedNameMask" varchar(64) COLLATE "default"
)
WITH (OIDS=FALSE);
-- Indexes structure for table estateban
-- ----------------------------
CREATE INDEX IF NOT EXISTS "ix_estateban" ON "public"."estateban" USING btree("EstateID" "pg_catalog"."int4_ops" ASC NULLS LAST);
COMMIT;
:VERSION 13
BEGIN TRASACTION;
-- ----------------------------
-- SEQUENCE estate_settings_id
-- ----------------------------
CREATE SEQUENCE IF NOT EXISTS "public"."estate_settings_id"
INCREMENT 100
MINVALUE 1
MAXVALUE 9223372036854775807
START 100
CACHE 1;
COMMIT;
:VERSION 14
BEGIN TRANSACTION;
ALTER TABLE "public"."estateban"
ADD COLUMN "banningUUID" uuid NOT NULL,
ADD COLUMN "banTime" int4 NOT NULL DEFAULT 0;
COMMIT;
:VERSION 15
BEGIN TRANSACTION;
ALTER TABLE "public"."estate_settings"
ADD COLUMN "AllowEnviromentOverride" bool NOT NULL;
COMMIT;

View file

@ -1,14 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE fsassets (
"id" uuid NOT NULL PRIMARY KEY,
"type" integer NOT NULL,
"hash" char(64) NOT NULL,
"create_time" integer NOT NULL DEFAULT '0',
"access_time" integer NOT NULL DEFAULT '0',
"asset_flags" integer NOT NULL DEFAULT '0'
);
COMMIT;

View file

@ -1,44 +0,0 @@
: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;

View file

@ -1,242 +0,0 @@
: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;

View file

@ -1,60 +0,0 @@
: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;

View file

@ -1,17 +0,0 @@
: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;

View file

@ -1,45 +0,0 @@
: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;
:VERSION 3 # --------------------------
BEGIN;
-- dropping the table here as there most likely is only one record in the table at the time of migration
DROP TABLE IF EXISTS "public"."im_offline";
CREATE TABLE "public"."im_offline" (
"ID" serial,
"PrincipalID" uuid NOT NULL,
"Message" text NOT NULL COLLATE "default",
"TMStamp" timestamp(6) NOT NULL DEFAULT clock_timestamp(),
"FromID" uuid NOT NULL
)
WITH (OIDS=FALSE);
ALTER TABLE "public"."im_offline" ADD PRIMARY KEY ("ID","PrincipalID","FromID") NOT DEFERRABLE INITIALLY IMMEDIATE;
COMMIT;

View file

@ -1,220 +0,0 @@
: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;
:VERSION 10
BEGIN TRANSACTION;
Alter table inventoryitems Rename Column "SaleType" to "saleType";
Commit;

View file

@ -1,16 +0,0 @@
: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;

View file

@ -1,42 +0,0 @@
: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");
ALTER TABLE Presence ADD "LastSeen" Timestamp;
COMMIT;
:VERSION 3 # --------------------------
BEGIN;
CREATE INDEX RegionID ON Presence("RegionID");
COMMIT;
:VERSION 4 # Making sure LastSeen is actually defined in the table as it most likely erred in the double version 2 migration above
BEGIN;
ALTER TABLE Presence
DROP COLUMN IF EXISTS "LastSeen",
ADD COLUMN "LastSeen" Timestamp;
COMMIT;

File diff suppressed because it is too large Load diff

View file

@ -1,57 +0,0 @@
: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;
:VERSION 5
BEGIN TRANSACTION;
ALTER TABLE UserAccounts ADD "active" integer NOT NULL DEFAULT 1;
COMMIT;

View file

@ -1,163 +0,0 @@
: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;
:VERSION 3 # -------------------------------
begin;
CREATE TABLE usersettings (
"useruuid" char(36) NOT NULL,
"imviaemail" bytea NOT NULL,
"visible" bytea NOT NULL,
PRIMARY KEY ("useruuid")
);
commit;
:VERSION 4
BEGIN;
-- Classifieds
ALTER TABLE classifieds DROP CONSTRAINT classifiedspk;
ALTER TABLE classifieds ALTER COLUMN classifieduuid SET DATA TYPE uuid using classifieduuid::uuid;
ALTER TABLE classifieds ALTER COLUMN creatoruuid SET DATA TYPE uuid using creatoruuid::uuid;
ALTER TABLE classifieds ALTER COLUMN parceluuid SET DATA TYPE uuid using parceluuid::uuid;
ALTER TABLE classifieds ALTER COLUMN snapshotuuid SET DATA TYPE uuid using snapshotuuid::uuid;
ALTER TABLE classifieds ADD CONSTRAINT classifiedspk PRIMARY KEY (classifieduuid);
-- Notes
ALTER TABLE usernotes DROP CONSTRAINT usernoteuk;
ALTER TABLE usernotes ALTER COLUMN useruuid SET DATA TYPE uuid USING useruuid::uuid;
ALTER TABLE usernotes ALTER COLUMN targetuuid SET DATA TYPE uuid USING targetuuid::uuid;
ALTER TABLE usernotes ADD CONSTRAINT usernoteuk UNIQUE (useruuid,targetuuid);
-- Userpicks
ALTER TABLE userpicks DROP CONSTRAINT userpicks_pkey;
ALTER TABLE userpicks ALTER COLUMN pickuuid SET DATA TYPE uuid USING pickuuid::uuid;
ALTER TABLE userpicks ALTER COLUMN creatoruuid SET DATA TYPE uuid USING creatoruuid::uuid;
ALTER TABLE userpicks ALTER COLUMN parceluuid SET DATA TYPE uuid USING parceluuid::uuid;
ALTER TABLE userpicks ALTER COLUMN parceluuid SET DATA TYPE uuid USING parceluuid::uuid;
ALTER TABLE userpicks ADD PRIMARY KEY (pickuuid);
-- Userprofile
ALTER TABLE userprofile DROP CONSTRAINT userprofile_pkey;
ALTER TABLE userprofile ALTER COLUMN useruuid SET DATA TYPE uuid USING useruuid::uuid;
ALTER TABLE userprofile ALTER COLUMN "profilePartner" SET DATA TYPE uuid USING "profilePartner"::uuid;
-- Force column conversions
ALTER TABLE userprofile ALTER COLUMN "profileAllowPublish" SET DATA TYPE boolean USING CASE WHEN false THEN false ELSE true END;
ALTER TABLE userprofile ALTER COLUMN "profileMaturePublish" SET DATA TYPE boolean USING CASE WHEN false THEN false ELSE true END;
ALTER TABLE userprofile ALTER COLUMN "profileImage" SET DATA TYPE uuid USING "profileImage"::uuid;
ALTER TABLE userprofile ALTER COLUMN "profileFirstImage" SET DATA TYPE uuid USING "profileFirstImage"::uuid;
ALTER TABLE userprofile ADD PRIMARY KEY (useruuid);
-- Userdata
ALTER TABLE userdata DROP CONSTRAINT userdata_pkey;
ALTER TABLE userdata ALTER COLUMN "UserId" SET DATA TYPE uuid USING "UserId"::uuid;
ALTER TABLE userdata ALTER COLUMN "UserId" SET DATA TYPE uuid USING "UserId"::uuid;
ALTER TABLE userdata ADD PRIMARY KEY ("UserId","TagId");
-- Usersettings
ALTER TABLE usersettings DROP CONSTRAINT usersettings_pkey;
ALTER TABLE usersettings ALTER COLUMN useruuid SET DATA TYPE uuid USING useruuid::uuid;
ALTER TABLE usersettings ALTER COLUMN visible SET DATA TYPE boolean USING CASE WHEN false THEN false ELSE true END;
ALTER TABLE usersettings ADD COLUMN email varchar(254) NOT NULL;
ALTER TABLE usersettings ADD PRIMARY KEY (useruuid);
COMMIT;
:VERSION 5 # -------------------------------
BEGIN;
ALTER TABLE usersettings ALTER COLUMN imviaemail SET DATA TYPE boolean USING CASE WHEN false THEN false ELSE true END;
COMMIT;
:VERSION 6 # -------------------------------
BEGIN TRANSACTION;
ALTER TABLE userpicks ADD "gatekeeper" varchar(255) COLLATE "default";
COMMIT;

View file

@ -1,404 +0,0 @@
: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;

View file

@ -1,80 +0,0 @@
# -----------------
: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;
:VERSION 2
BEGIN;
ALTER TABLE xassetsmeta ALTER COLUMN "Local" SET DATA TYPE boolean USING CASE WHEN '0' THEN FALSE ELSE TRUE END;
ALTER TABLE xassetsmeta ALTER COLUMN "Temporary" SET DATA TYPE boolean USING CASE WHEN '0' THEN FALSE ELSE TRUE END;
ALTER TABLE xassetsmeta ALTER COLUMN "Hash" SET DATA TYPE char(66);
ALTER TABLE xassetsdata ALTER COLUMN "Hash" SET DATA TYPE char(66);
COMMIT;
:VERSION 3
BEGIN;
ALTER TABLE xassetsmeta RENAME COLUMN "ID" TO id;
ALTER TABLE xassetsmeta RENAME COLUMN "Hash" TO hash;
ALTER TABLE xassetsmeta RENAME COLUMN "Name" TO name;
ALTER TABLE xassetsmeta RENAME COLUMN "Description" TO description;
ALTER TABLE xassetsmeta RENAME COLUMN "Local" to local;
ALTER TABLE xassetsmeta RENAME COLUMN "Temporary" TO temporary;
ALTER TABLE xassetsmeta RENAME COLUMN "CreateTime" TO create_time;
ALTER TABLE xassetsmeta RENAME COLUMN "AccessTime" TO access_time;
ALTER TABLE xassetsmeta RENAME COLUMN "AssetFlags" TO asset_flags;
ALTER TABLE xassetsmeta RENAME COLUMN "CreatorID" TO creatorid;
ALTER TABLE xassetsmeta DROP CONSTRAINT xassetsmeta_pkey;
ALTER TABLE xassetsmeta ADD PRIMARY KEY (id);
ALTER TABLE xassetsdata RENAME COLUMN "Hash" TO hash;
ALTER TABLE xassetsdata RENAME COLUMN "Data" TO data;
ALTER TABLE xassetsdata DROP CONSTRAINT xassetsdata_pkey;
ALTER TABLE xassetsdata ADD PRIMARY KEY (hash);
COMMIT;
:VERSION 4
BEGIN;
ALTER TABLE xassetsmeta ALTER COLUMN id SET DATA TYPE uuid USING id::uuid;
ALTER TABLE xassetsmeta ALTER COLUMN hash SET DATA TYPE bytea USING hash::bytea;
ALTER TABLE xassetsdata ALTER COLUMN hash SET DATA TYPE bytea USING hash::bytea;
COMMIT;
:VERSION 5
BEGIN;
COMMIT;

View file

@ -1,211 +0,0 @@
: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;
:VERSION 3
BEGIN;
-- Not a pretty way to do this, but it did not work as-is
-- and nothing was found about converting between existing data
-- and the new type.
-- Since there should be nothing to preserve ...
DROP TABLE IF EXISTS os_groups_groups CASCADE;
CREATE TABLE os_groups_groups (
"GroupID" uuid PRIMARY KEY NOT NULL,
"Location" varchar(255) NOT NULL DEFAULT '',
"Name" varchar(255) NOT NULL DEFAULT '',
"Charter" text NOT NULL,
"InsigniaID" uuid NOT NULL,
"FounderID" uuid NOT NULL,
"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" uuid NOT NULL
);
DROP TABLE IF EXISTS os_groups_membership;
CREATE TABLE os_groups_membership (
"GroupID"uuid NOT NULL,
"PrincipalID" VARCHAR(255) NOT NULL DEFAULT '',
"SelectedRoleID" uuid NOT NULL,
"Contribution" integer NOT NULL DEFAULT '0',
"ListInProfile" integer NOT NULL DEFAULT '1',
"AcceptNotices" integer NOT NULL DEFAULT '1',
"AccessToken" uuid NOT NULL,
constraint os_groupmemberpk PRIMARY KEY ("GroupID", "PrincipalID")
);
DROP TABLE IF EXISTS os_groups_roles;
CREATE TABLE os_groups_roles (
"GroupID" uuid NOT NULL,
"RoleID" uuid NOT NULL,
"Name" varchar(255) NOT NULL DEFAULT '',
"Description" varchar(255) NOT NULL DEFAULT '',
"Title" varchar(255) NOT NULL DEFAULT '',
"Powers" varchar(36) NOT NULL DEFAULT '',
constraint os_grouprolepk PRIMARY KEY ("GroupID","RoleID")
);
DROP TABLE IF EXISTS os_groups_rolemembership;
CREATE TABLE os_groups_rolemembership (
"GroupID" uuid NOT NULL,
"RoleID" uuid NOT NULL,
"PrincipalID" VARCHAR(255) NOT NULL DEFAULT '',
constraint os_grouprolememberpk PRIMARY KEY ("GroupID","RoleID","PrincipalID")
);
DROP TABLE IF EXISTS os_groups_invites;
CREATE TABLE os_groups_invites (
"InviteID" uuid NOT NULL,
"GroupID" uuid NOT NULL,
"RoleID" uuid NOT NULL,
"PrincipalID" VARCHAR(255) NOT NULL DEFAULT '',
"TMStamp" timestamp NOT NULL DEFAULT now(),
constraint os_groupinvitespk PRIMARY KEY ("InviteID")
);
DROP TABLE IF EXISTS os_groups_notices;
CREATE TABLE os_groups_notices (
"GroupID" uuid NOT NULL,
"NoticeID" uuid NOT NULL,
"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" uuid NOT NULL,
"AttachmentOwnerID" varchar(255) NOT NULL DEFAULT '',
constraint os_groupsnoticespk PRIMARY KEY ("NoticeID")
);
DROP TABLE IF EXISTS os_groups_principals;
CREATE TABLE os_groups_principals (
"PrincipalID" VARCHAR(255) NOT NULL DEFAULT '',
"ActiveGroupID" uuid NOT NULL,
constraint os_groupprincpk PRIMARY KEY ("PrincipalID")
);
COMMIT;
:VERSION 4
BEGIN;
ALTER TABLE IF EXISTS os_groups_notices
ALTER COLUMN "AttachmentItemID" SET DEFAULT '00000000-0000-0000-0000-000000000000'
;
COMMIT;

View file

@ -1,52 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AssemblyTitle>OpenSim.Data.SQLite</AssemblyTitle>
<Company>http://opensimulator.org</Company>
<Product>OpenSim.Data.SQLite</Product>
<Copyright>Copyright (c) OpenSimulator.org Developers 2007-2009</Copyright>
</PropertyGroup>
<ItemGroup>
<Reference Include="OpenMetaverse">
<HintPath>..\..\bin\OpenMetaverse.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="OpenMetaverse.StructuredData">
<HintPath>..\..\bin\OpenMetaverse.StructuredData.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="OpenMetaverseTypes">
<HintPath>..\..\bin\OpenMetaverseTypes.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Source\OpenSim.Data\OpenSim.Data.csproj" />
<ProjectReference Include="..\..\Source\OpenSim.Framework\OpenSim.Framework.csproj" />
<ProjectReference Include="..\..\Source\OpenSim.Framework.Console\OpenSim.Framework.Console.csproj" />
<ProjectReference Include="..\..\Source\OpenSim.Region.Framework\OpenSim.Region.Framework.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\001_GridUserStore.sql" />
<EmbeddedResource Include="Resources\AgentPrefs.migrations" />
<EmbeddedResource Include="Resources\AssetStore.migrations" />
<EmbeddedResource Include="Resources\AuthStore.migrations" />
<EmbeddedResource Include="Resources\Avatar.migrations" />
<EmbeddedResource Include="Resources\EstateStore.migrations" />
<EmbeddedResource Include="Resources\FriendsStore.migrations" />
<EmbeddedResource Include="Resources\HGTravelStore.migrations" />
<EmbeddedResource Include="Resources\MuteListStore.migrations" />
<EmbeddedResource Include="Resources\RegionStore.migrations" />
<EmbeddedResource Include="Resources\UserAccount.migrations" />
<EmbeddedResource Include="Resources\UserProfiles.migrations" />
<EmbeddedResource Include="Resources\XInventoryStore.migrations" />
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="8.0.0" />
<PackageReference Include="RawScape.Nini" Version="1.0.0" />
<PackageReference Include="System.Data.SQLite" Version="1.0.118" />
</ItemGroup>
</Project>

View file

@ -1,16 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE GridUser (
UserID VARCHAR(255) 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;

View file

@ -1,36 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE `AgentPrefs` (
`PrincipalID` CHAR(36) NOT NULL,
`AccessPrefs` CHAR(2) NOT NULL DEFAULT 'M',
`HoverHeight` DOUBLE(30, 27) NOT NULL DEFAULT 0,
`Language` CHAR(5) NOT NULL DEFAULT 'en-us',
`LanguageIsPublic` BOOLEAN NOT NULL DEFAULT 1,
`PermEveryone` INT(6) NOT NULL DEFAULT 0,
`PermGroup` INT(6) NOT NULL DEFAULT 0,
`PermNextOwner` INT(6) NOT NULL DEFAULT 532480,
UNIQUE (`PrincipalID`),
PRIMARY KEY(`PrincipalID`));
COMMIT;
:VERSION 2
BEGIN;
CREATE TABLE AgentPrefs(
PrincipalID CHAR(36) NOT NULL,
AccessPrefs CHAR(2) NOT NULL DEFAULT 'M',
HoverHeight DOUBLE(30, 27) NOT NULL DEFAULT 0,
Language CHAR(5) NOT NULL DEFAULT 'en-us',
LanguageIsPublic BOOLEAN NOT NULL DEFAULT 1,
PermEveryone INT(6) NOT NULL DEFAULT 0,
PermGroup INT(6) NOT NULL DEFAULT 0,
PermNextOwner INT(6) NOT NULL DEFAULT 532480,
UNIQUE(PrincipalID),
PRIMARY KEY(PrincipalID)
);
COMMIT;

View file

@ -1,18 +0,0 @@
:VERSION 6
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS assets(
UUID NOT NULL PRIMARY KEY,
Name,
Description,
Type,
Local,
Temporary,
asset_flags INTEGER NOT NULL DEFAULT 0,
CreatorID varchar(128) default '',
Data);
COMMIT;

View file

@ -1,29 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE auth (
UUID char(36) NOT NULL,
passwordHash char(32) NOT NULL default '',
passwordSalt char(32) NOT NULL default '',
webLoginKey varchar(255) NOT NULL default '',
accountType VARCHAR(32) NOT NULL DEFAULT 'UserAccount',
PRIMARY KEY (`UUID`)
);
CREATE TABLE tokens (
UUID char(36) NOT NULL,
token varchar(255) NOT NULL,
validity datetime NOT NULL
);
COMMIT;
:VERSION 2
BEGIN TRANSACTION;
INSERT INTO auth (UUID, passwordHash, passwordSalt, webLoginKey) SELECT `UUID` AS UUID, `passwordHash` AS passwordHash, `passwordSalt` AS passwordSalt, `webLoginKey` AS webLoginKey FROM users;
COMMIT;

View file

@ -1,11 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE Avatars (
PrincipalID CHAR(36) NOT NULL,
Name VARCHAR(32) NOT NULL,
Value VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY(PrincipalID, Name));
COMMIT;

View file

@ -1,83 +0,0 @@
:VERSION 10
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS estate_groups (
EstateID int(10) NOT NULL,
uuid char(36) NOT NULL
);
CREATE INDEX estate_groups_estate_id on estate_groups(EstateID);
CREATE TABLE IF NOT EXISTS estate_managers (
EstateID int(10) NOT NULL,
uuid char(36) NOT NULL
);
CREATE INDEX estate_managers_estate_id on estate_managers(EstateID);
CREATE TABLE IF NOT EXISTS estate_map (
RegionID char(36) NOT NULL default '00000000-0000-0000-0000-000000000000',
EstateID int(11) NOT NULL
);
CREATE INDEX estate_map_estate_id on estate_map(EstateID);
CREATE UNIQUE INDEX estate_map_region_id on estate_map(RegionID);
CREATE TABLE IF NOT EXISTS estate_settings (
EstateID INTEGER NOT NULL PRIMARY KEY,
EstateName varchar(64) default NULL,
AbuseEmailToEstateOwner tinyint(4) NOT NULL,
DenyAnonymous tinyint(4) NOT NULL,
ResetHomeOnTeleport tinyint(4) NOT NULL,
FixedSun tinyint(4) NOT NULL,
DenyTransacted tinyint(4) NOT NULL,
BlockDwell tinyint(4) NOT NULL,
DenyIdentified tinyint(4) NOT NULL,
AllowVoice tinyint(4) NOT NULL,
UseGlobalTime tinyint(4) NOT NULL,
PricePerMeter int(11) NOT NULL,
TaxFree tinyint(4) NOT NULL,
AllowDirectTeleport tinyint(4) NOT NULL,
RedirectGridX int(11) NOT NULL,
RedirectGridY int(11) NOT NULL,
ParentEstateID int(10) NOT NULL,
SunPosition double NOT NULL,
EstateSkipScripts tinyint(4) NOT NULL,
BillableFactor float NOT NULL,
PublicAccess tinyint(4) NOT NULL,
AbuseEmail varchar(255) not null default '',
EstateOwner varchar(36) not null default '',
DenyMinors tinyint not null default 0,
AllowLandmark tinyint not null default '1',
AllowParcelChanges tinyint not null default '1',
AllowSetHome tinyint not null default '1');
CREATE TABLE IF NOT EXISTS estate_users (
EstateID int(10) NOT NULL,
uuid char(36) NOT NULL
);
CREATE INDEX estate_users_estate_id on estate_users(EstateID);
CREATE TABLE IF NOT EXISTS estateban (
EstateID int(10) NOT NULL,
bannedUUID varchar(36) NOT NULL,
bannedIp varchar(16) NOT NULL,
bannedIpHostMask varchar(16) NOT NULL,
bannedNameMask varchar(64) default NULL
);
CREATE INDEX estate_ban_estate_id on estateban(EstateID);
COMMIT;
:VERSION 11
BEGIN;
ALTER TABLE `estateban` ADD COLUMN `banningUUID` varchar(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000';
ALTER TABLE `estateban` ADD COLUMN `banTime` integer NOT NULL DEFAULT 0;
COMMIT;
:VERSION 12
BEGIN;
ALTER TABLE `estate_settings`
ADD COLUMN `AllowEnviromentOverride` tinyint not null default 0;
COMMIT;

View file

@ -1,20 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE `Friends` (
`PrincipalID` CHAR(36) NOT NULL,
`Friend` VARCHAR(255) NOT NULL,
`Flags` VARCHAR(16) NOT NULL DEFAULT 0,
`Offered` VARCHAR(32) NOT NULL DEFAULT 0,
PRIMARY KEY(`PrincipalID`, `Friend`));
COMMIT;
:VERSION 2
BEGIN TRANSACTION;
INSERT INTO `Friends` SELECT `ownerID`, `friendID`, `friendPerms`, 0 FROM `userfriends`;
COMMIT;

View file

@ -1,18 +0,0 @@
:VERSION 2 # --------------------------
BEGIN;
CREATE TABLE hg_traveling_data(
SessionID VARCHAR(36) NOT NULL,
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 DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(SessionID),
UNIQUE(UserID)
);
COMMIT;

View file

@ -1,16 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE MuteList (
AgentID char(36) NOT NULL,
MuteID char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
MuteName varchar(64) NOT NULL DEFAULT '',
MuteType int(11) NOT NULL DEFAULT '1',
MuteFlags int(11) NOT NULL DEFAULT '0',
Stamp int(11) NOT NULL,
UNIQUE (AgentID, MuteID, MuteName),
PRIMARY KEY(AgentID)
);
COMMIT;

View file

@ -1,412 +0,0 @@
:VERSION 31
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS prims(
UUID varchar(255) primary key,
RegionUUID varchar(255),
CreationDate integer,
Name varchar(255),
SceneGroupID varchar(255),
Text varchar(255),
Description varchar(255),
SitName varchar(255),
TouchName varchar(255),
CreatorID varchar(255),
OwnerID varchar(255),
GroupID varchar(255),
LastOwnerID varchar(255),
OwnerMask integer,
NextOwnerMask integer,
GroupMask integer,
EveryoneMask integer,
BaseMask integer,
PositionX float,
PositionY float,
PositionZ float,
GroupPositionX float,
GroupPositionY float,
GroupPositionZ float,
VelocityX float,
VelocityY float,
VelocityZ float,
AngularVelocityX float,
AngularVelocityY float,
AngularVelocityZ float,
AccelerationX float,
AccelerationY float,
AccelerationZ float,
RotationX float,
RotationY float,
RotationZ float,
RotationW float,
ObjectFlags integer,
SitTargetOffsetX float NOT NULL default 0,
SitTargetOffsetY float NOT NULL default 0,
SitTargetOffsetZ float NOT NULL default 0,
SitTargetOrientW float NOT NULL default 0,
SitTargetOrientX float NOT NULL default 0,
SitTargetOrientY float NOT NULL default 0,
SitTargetOrientZ float NOT NULL default 0,
ColorR integer not null default 0,
ColorG integer not null default 0,
ColorB integer not null default 0,
ColorA integer not null default 0,
ClickAction integer not null default 0,
PayPrice integer not null default 0,
PayButton1 integer not null default 0,
PayButton2 integer not null default 0,
PayButton3 integer not null default 0,
PayButton4 integer not null default 0,
LoopedSound varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000',
LoopedSoundGain float NOT NULL default 0,
TextureAnimation string,
ParticleSystem string,
OmegaX float NOT NULL default 0,
OmegaY float NOT NULL default 0,
OmegaZ float NOT NULL default 0,
CameraEyeOffsetX float NOT NULL default 0,
CameraEyeOffsetY float NOT NULL default 0,
CameraEyeOffsetZ float NOT NULL default 0,
CameraAtOffsetX float NOT NULL default 0,
CameraAtOffsetY float NOT NULL default 0,
CameraAtOffsetZ float NOT NULL default 0,
ForceMouselook string NOT NULL default 0,
ScriptAccessPin INTEGER NOT NULL default 0,
AllowedDrop INTEGER NOT NULL default 0,
DieAtEdge string NOT NULL default 0,
SalePrice INTEGER NOT NULL default 0,
SaleType string NOT NULL default 0,
Material INTEGER NOT NULL default 3,
CollisionSound varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000',
CollisionSoundVolume float NOT NULL default 0,
VolumeDetect INTEGER NOT NULL DEFAULT 0,
MediaURL varchar(255),
DynAttrs TEXT,
`PhysicsShapeType` tinyint(4) NOT NULL default '0',
`Density` double NOT NULL default '1000',
`GravityModifier` double NOT NULL default '1',
`Friction` double NOT NULL default '0.6',
`Restitution` double NOT NULL default '0.5',
`KeyframeMotion` blob,
AttachedPosX double default '0',
AttachedPosY double default '0',
AttachedPosZ double default '0');
CREATE TABLE IF NOT EXISTS primshapes(
UUID varchar(255) primary key,
Shape integer,
ScaleX float,
ScaleY float,
ScaleZ float,
PCode integer,
PathBegin integer,
PathEnd integer,
PathScaleX integer,
PathScaleY integer,
PathShearX integer,
PathShearY integer,
PathSkew integer,
PathCurve integer,
PathRadiusOffset integer,
PathRevolutions integer,
PathTaperX integer,
PathTaperY integer,
PathTwist integer,
PathTwistBegin integer,
ProfileBegin integer,
ProfileEnd integer,
ProfileCurve integer,
ProfileHollow integer,
Texture blob,
ExtraParams blob,
State Integer NOT NULL default 0,
Media TEXT,
LastAttachPoint int not null default '0');
CREATE TABLE IF NOT EXISTS primitems(
itemID varchar(255) primary key,
primID varchar(255),
assetID varchar(255),
parentFolderID varchar(255),
invType integer,
assetType integer,
name varchar(255),
description varchar(255),
creationDate integer,
creatorID varchar(255),
ownerID varchar(255),
lastOwnerID varchar(255),
groupID varchar(255),
nextPermissions string,
currentPermissions string,
basePermissions string,
everyonePermissions string,
groupPermissions string,
flags integer not null default 0);
CREATE TABLE IF NOT EXISTS terrain(
RegionUUID varchar(255),
Revision integer,
Heightfield blob);
CREATE TABLE IF NOT EXISTS land(
UUID varchar(255) primary key,
RegionUUID varchar(255),
LocalLandID string,
Bitmap blob,
Name varchar(255),
Desc varchar(255),
OwnerUUID varchar(255),
IsGroupOwned string,
Area integer,
AuctionID integer,
Category integer,
ClaimDate integer,
ClaimPrice integer,
GroupUUID varchar(255),
SalePrice integer,
LandStatus integer,
LandFlags string,
LandingType string,
MediaAutoScale string,
MediaTextureUUID varchar(255),
MediaURL varchar(255),
MusicURL varchar(255),
PassHours float,
PassPrice string,
SnapshotUUID varchar(255),
UserLocationX float,
UserLocationY float,
UserLocationZ float,
UserLookAtX float,
UserLookAtY float,
UserLookAtZ float,
AuthbuyerID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000',
OtherCleanTime INTEGER NOT NULL default 0,
Dwell INTEGER NOT NULL default 0,
`MediaType` VARCHAR(32) NOT NULL DEFAULT 'none/none',
`MediaDescription` VARCHAR(255) NOT NULL DEFAULT '',
`MediaSize` VARCHAR(16) NOT NULL DEFAULT '0,0',
`MediaLoop` BOOLEAN NOT NULL DEFAULT FALSE,
`ObscureMusic` BOOLEAN NOT NULL DEFAULT FALSE,
`ObscureMedia` BOOLEAN NOT NULL DEFAULT FALSE);
CREATE TABLE IF NOT EXISTS landaccesslist(
LandUUID varchar(255),
AccessUUID varchar(255),
Flags string);
CREATE TABLE IF NOT EXISTS regionban(
regionUUID varchar (255),
bannedUUID varchar (255),
bannedIp varchar (255),
bannedIpHostMask varchar (255)
);
CREATE TABLE IF NOT EXISTS regionsettings (
regionUUID char(36) NOT NULL,
block_terraform int(11) NOT NULL,
block_fly int(11) NOT NULL,
allow_damage int(11) NOT NULL,
restrict_pushing int(11) NOT NULL,
allow_land_resell int(11) NOT NULL,
allow_land_join_divide int(11) NOT NULL,
block_show_in_search int(11) NOT NULL,
agent_limit int(11) NOT NULL,
object_bonus float NOT NULL,
maturity int(11) NOT NULL,
disable_scripts int(11) NOT NULL,
disable_collisions int(11) NOT NULL,
disable_physics int(11) NOT NULL,
terrain_texture_1 char(36) NOT NULL,
terrain_texture_2 char(36) NOT NULL,
terrain_texture_3 char(36) NOT NULL,
terrain_texture_4 char(36) NOT NULL,
elevation_1_nw float NOT NULL,
elevation_2_nw float NOT NULL,
elevation_1_ne float NOT NULL,
elevation_2_ne float NOT NULL,
elevation_1_se float NOT NULL,
elevation_2_se float NOT NULL,
elevation_1_sw float NOT NULL,
elevation_2_sw float NOT NULL,
water_height float NOT NULL,
terrain_raise_limit float NOT NULL,
terrain_lower_limit float NOT NULL,
use_estate_sun int(11) NOT NULL,
fixed_sun int(11) NOT NULL,
sun_position float NOT NULL,
covenant char(36) default NULL,
sandbox tinyint(4) NOT NULL,
sunvectorx double NOT NULL default 0,
sunvectory double NOT NULL default 0,
sunvectorz double NOT NULL default 0,
map_tile_ID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000',
covenant_datetime INTEGER NOT NULL default 0,
`TelehubObject` varchar(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
`parcel_tile_ID` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
PRIMARY KEY (regionUUID)
);
CREATE TABLE IF NOT EXISTS regionwindlight (
region_id VARCHAR(36) NOT NULL DEFAULT '000000-0000-0000-0000-000000000000' PRIMARY KEY,
water_color_r FLOAT NOT NULL DEFAULT '4.000000',
water_color_g FLOAT NOT NULL DEFAULT '38.000000',
water_color_b FLOAT NOT NULL DEFAULT '64.000000',
water_color_i FLOAT NOT NULL DEFAULT '1.000000',
water_fog_density_exponent FLOAT NOT NULL DEFAULT '4.0',
underwater_fog_modifier FLOAT NOT NULL DEFAULT '0.25',
reflection_wavelet_scale_1 FLOAT NOT NULL DEFAULT '2.0',
reflection_wavelet_scale_2 FLOAT NOT NULL DEFAULT '2.0',
reflection_wavelet_scale_3 FLOAT NOT NULL DEFAULT '2.0',
fresnel_scale FLOAT NOT NULL DEFAULT '0.40',
fresnel_offset FLOAT NOT NULL DEFAULT '0.50',
refract_scale_above FLOAT NOT NULL DEFAULT '0.03',
refract_scale_below FLOAT NOT NULL DEFAULT '0.20',
blur_multiplier FLOAT NOT NULL DEFAULT '0.040',
big_wave_direction_x FLOAT NOT NULL DEFAULT '1.05',
big_wave_direction_y FLOAT NOT NULL DEFAULT '-0.42',
little_wave_direction_x FLOAT NOT NULL DEFAULT '1.11',
little_wave_direction_y FLOAT NOT NULL DEFAULT '-1.16',
normal_map_texture VARCHAR(36) NOT NULL DEFAULT '822ded49-9a6c-f61c-cb89-6df54f42cdf4',
horizon_r FLOAT NOT NULL DEFAULT '0.25',
horizon_g FLOAT NOT NULL DEFAULT '0.25',
horizon_b FLOAT NOT NULL DEFAULT '0.32',
horizon_i FLOAT NOT NULL DEFAULT '0.32',
haze_horizon FLOAT NOT NULL DEFAULT '0.19',
blue_density_r FLOAT NOT NULL DEFAULT '0.12',
blue_density_g FLOAT NOT NULL DEFAULT '0.22',
blue_density_b FLOAT NOT NULL DEFAULT '0.38',
blue_density_i FLOAT NOT NULL DEFAULT '0.38',
haze_density FLOAT NOT NULL DEFAULT '0.70',
density_multiplier FLOAT NOT NULL DEFAULT '0.18',
distance_multiplier FLOAT NOT NULL DEFAULT '0.8',
max_altitude INTEGER NOT NULL DEFAULT '1605',
sun_moon_color_r FLOAT NOT NULL DEFAULT '0.24',
sun_moon_color_g FLOAT NOT NULL DEFAULT '0.26',
sun_moon_color_b FLOAT NOT NULL DEFAULT '0.30',
sun_moon_color_i FLOAT NOT NULL DEFAULT '0.30',
sun_moon_position FLOAT NOT NULL DEFAULT '0.317',
ambient_r FLOAT NOT NULL DEFAULT '0.35',
ambient_g FLOAT NOT NULL DEFAULT '0.35',
ambient_b FLOAT NOT NULL DEFAULT '0.35',
ambient_i FLOAT NOT NULL DEFAULT '0.35',
east_angle FLOAT NOT NULL DEFAULT '0.00',
sun_glow_focus FLOAT NOT NULL DEFAULT '0.10',
sun_glow_size FLOAT NOT NULL DEFAULT '1.75',
scene_gamma FLOAT NOT NULL DEFAULT '1.00',
star_brightness FLOAT NOT NULL DEFAULT '0.00',
cloud_color_r FLOAT NOT NULL DEFAULT '0.41',
cloud_color_g FLOAT NOT NULL DEFAULT '0.41',
cloud_color_b FLOAT NOT NULL DEFAULT '0.41',
cloud_color_i FLOAT NOT NULL DEFAULT '0.41',
cloud_x FLOAT NOT NULL DEFAULT '1.00',
cloud_y FLOAT NOT NULL DEFAULT '0.53',
cloud_density FLOAT NOT NULL DEFAULT '1.00',
cloud_coverage FLOAT NOT NULL DEFAULT '0.27',
cloud_scale FLOAT NOT NULL DEFAULT '0.42',
cloud_detail_x FLOAT NOT NULL DEFAULT '1.00',
cloud_detail_y FLOAT NOT NULL DEFAULT '0.53',
cloud_detail_density FLOAT NOT NULL DEFAULT '0.12',
cloud_scroll_x FLOAT NOT NULL DEFAULT '0.20',
cloud_scroll_x_lock INTEGER NOT NULL DEFAULT '0',
cloud_scroll_y FLOAT NOT NULL DEFAULT '0.01',
cloud_scroll_y_lock INTEGER NOT NULL DEFAULT '0',
draw_classic_clouds INTEGER NOT NULL DEFAULT '1');
CREATE TABLE IF NOT EXISTS `spawn_points` (
`RegionID` varchar(36) NOT NULL DEFAULT '000000-0000-0000-0000-000000000000',
`Yaw` float NOT NULL,
`Pitch` float NOT NULL,
`Distance` float NOT NULL
);
CREATE TABLE IF NOT EXISTS `regionenvironment` (
`region_id` varchar(36) NOT NULL DEFAULT '000000-0000-0000-0000-000000000000' PRIMARY KEY,
`llsd_settings` TEXT NOT NULL
);
COMMIT;
:VERSION 32 #---- avination fields plus a few others
BEGIN;
ALTER TABLE `prims` ADD COLUMN `PassTouches` BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE `prims` ADD COLUMN `PassCollisions`BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE `prims` ADD COLUMN `Vehicle` TEXT default NULL;
ALTER TABLE `regionsettings` ADD COLUMN `block_search` BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE `regionsettings` ADD COLUMN `casino` BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE `land` ADD COLUMN `SeeAVs` BOOLEAN NOT NULL DEFAULT TRUE;
ALTER TABLE `land` ADD COLUMN `AnyAVSounds` BOOLEAN NOT NULL DEFAULT TRUE;
ALTER TABLE `land` ADD COLUMN `GroupAVSounds` BOOLEAN NOT NULL DEFAULT TRUE;
COMMIT;
:VERSION 33 #---- Rotation axis locks
BEGIN;
ALTER TABLE prims ADD COLUMN `RotationAxisLocks` tinyint(4) NOT NULL default '0';
COMMIT;
:VERSION 34 #---- add baked terrain store
BEGIN;
CREATE TABLE IF NOT EXISTS bakedterrain(
RegionUUID varchar(255),
Revision integer,
Heightfield blob);
COMMIT;
:VERSION 35 #----- Add RezzerID field in table prims
BEGIN;
ALTER TABLE `prims` ADD COLUMN `RezzerID` char(36) DEFAULT NULL;
COMMIT;
:VERSION 36 #----- Add physics inertia data
BEGIN;
ALTER TABLE `prims` ADD COLUMN `PhysInertia` TEXT default NULL;
COMMIT;
:VERSION 37 #----- Add standtarget and sit range
BEGIN;
ALTER TABLE `prims` ADD COLUMN `standtargetx` float NOT NULL DEFAULT '0.0';
ALTER TABLE `prims` ADD COLUMN `standtargety` float NOT NULL DEFAULT '0.0';
ALTER TABLE `prims` ADD COLUMN `standtargetz` float NOT NULL DEFAULT '0.0';
ALTER TABLE `prims` ADD COLUMN `sitactrange` float NOT NULL DEFAULT '0.0';
COMMIT;
:VERSION 38 #----- Add pseudo CRC and region cache id
BEGIN;
ALTER TABLE `prims` ADD COLUMN `pseudocrc` integer DEFAULT '0';
ALTER TABLE `regionsettings` ADD COLUMN `cacheID` char(36) DEFAULT NULL;
COMMIT;
:VERSION 39 #----- parcel environment store
BEGIN;
ALTER TABLE `land` ADD COLUMN `environment` TEXT default NULL;
COMMIT;
:VERSION 40 #----- sop animations and materials
BEGIN;
ALTER TABLE `prims` ADD COLUMN `sopanims` blob default NULL;
ALTER TABLE `primshapes` ADD COLUMN `MatOvrd` blob default NULL;
COMMIT;
:VERSION 41 #----- add linkset data storage column
BEGIN;
ALTER TABLE `prims` ADD COLUMN `linksetdata` TEXT default NULL;
COMMIT;

View file

@ -1,35 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
-- useraccounts table
CREATE TABLE UserAccounts (
PrincipalID CHAR(36) primary key,
ScopeID CHAR(36) NOT NULL,
FirstName VARCHAR(64) NOT NULL,
LastName VARCHAR(64) NOT NULL,
Email VARCHAR(64),
ServiceURLs TEXT,
Created INT(11),
UserLevel integer NOT NULL DEFAULT 0,
UserFlags integer NOT NULL DEFAULT 0,
UserTitle varchar(64) NOT NULL DEFAULT ''
);
COMMIT;
: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, surname AS LastName, '' as Email, '' AS ServiceURLs, created as Created FROM users;
COMMIT;
:VERSION 3 # -------------------------
BEGIN;
ALTER TABLE `UserAccounts` ADD `active` BOOLEAN NOT NULL DEFAULT TRUE;
COMMIT;

View file

@ -1,102 +0,0 @@
:VERSION 1 # -------------------------------
begin;
CREATE TABLE IF NOT EXISTS classifieds (
classifieduuid char(36) NOT NULL PRIMARY KEY,
creatoruuid char(36) NOT NULL,
creationdate int(20) NOT NULL,
expirationdate int(20) NOT NULL,
category varchar(20) NOT NULL,
name varchar(255) NOT NULL,
description text NOT NULL,
parceluuid char(36) NOT NULL,
parentestate int(11) NOT NULL,
snapshotuuid char(36) NOT NULL,
simname varchar(255) NOT NULL,
posglobal varchar(255) NOT NULL,
parcelname varchar(255) NOT NULL,
classifiedflags int(8) NOT NULL,
priceforlisting int(5) NOT NULL
);
commit;
begin;
CREATE TABLE IF NOT EXISTS usernotes (
useruuid varchar(36) NOT NULL,
targetuuid varchar(36) NOT NULL,
notes text NOT NULL,
UNIQUE (useruuid,targetuuid) ON CONFLICT REPLACE
);
commit;
begin;
CREATE TABLE IF NOT EXISTS userpicks (
pickuuid varchar(36) NOT NULL PRIMARY KEY,
creatoruuid varchar(36) NOT NULL,
toppick int 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 int(2) NOT NULL,
enabled int NOT NULL
);
commit;
begin;
CREATE TABLE IF NOT EXISTS userprofile (
useruuid varchar(36) NOT NULL PRIMARY KEY,
profilePartner varchar(36) NOT NULL,
profileAllowPublish binary(1) NOT NULL,
profileMaturePublish binary(1) NOT NULL,
profileURL varchar(255) NOT NULL,
profileWantToMask int(3) NOT NULL,
profileWantToText text NOT NULL,
profileSkillsMask int(3) 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
);
commit;
:VERSION 2 # -------------------------------
begin;
CREATE TABLE IF NOT EXISTS userdata (
UserId char(36) NOT NULL,
TagId varchar(64) NOT NULL,
DataKey varchar(255),
DataVal varchar(255),
PRIMARY KEY (UserId,TagId)
);
commit;
:VERSION 3 # -------------------------------
begin;
CREATE TABLE IF NOT EXISTS usersettings (
useruuid char(36) NOT NULL,
imviaemail binary(1) NOT NULL,
visible binary(1) NOT NULL,
email varchar(254) NOT NULL,
PRIMARY KEY (useruuid)
)
commit;

View file

@ -1,49 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE inventoryfolders(
folderName varchar(64),
type integer,
version integer,
folderID varchar(36) primary key,
agentID varchar(36) not null default '00000000-0000-0000-0000-000000000000',
parentFolderID varchar(36) not null default '00000000-0000-0000-0000-000000000000');
CREATE TABLE inventoryitems(
assetID varchar(36),
assetType integer,
inventoryName varchar(64),
inventoryDescription varchar(128),
inventoryNextPermissions integer,
inventoryCurrentPermissions integer,
invType integer,
creatorID varchar(128),
inventoryBasePermissions integer,
inventoryEveryOnePermissions integer,
salePrice integer default 99,
saleType integer default 0,
creationDate integer default 2000,
groupID varchar(36) default '00000000-0000-0000-0000-000000000000',
groupOwned integer default 0,
flags integer default 0,
inventoryID varchar(36) primary key,
parentFolderID varchar(36) not null default '00000000-0000-0000-0000-000000000000',
avatarID varchar(36) not null default '00000000-0000-0000-0000-000000000000',
inventoryGroupPermissions integer not null default 0);
create index inventoryfolders_agentid on inventoryfolders(agentID);
create index inventoryfolders_parentid on inventoryfolders(parentFolderID);
create index inventoryitems_parentfolderid on inventoryitems(parentFolderID);
create index inventoryitems_avatarid on inventoryitems(avatarID);
COMMIT;
:VERSION 2
BEGIN TRANSACTION;
INSERT INTO inventoryfolders (folderName, type, version, folderID, agentID, parentFolderID) SELECT `name` AS folderName, `type` AS type, `version` AS version, `UUID` AS folderID, `agentID` AS agentID, `parentID` AS parentFolderID from old.inventoryfolders;
INSERT INTO inventoryitems (assetID, assetType, inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType, creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, salePrice, saleType, creationDate, groupID, groupOwned, flags, inventoryID, parentFolderID, avatarID, inventoryGroupPermissions) SELECT `assetID`, `assetType` AS assetType, `inventoryName` AS inventoryName, `inventoryDescription` AS inventoryDescription, `inventoryNextPermissions` AS inventoryNextPermissions, `inventoryCurrentPermissions` AS inventoryCurrentPermissions, `invType` AS invType, `creatorsID` AS creatorID, `inventoryBasePermissions` AS inventoryBasePermissions, `inventoryEveryOnePermissions` AS inventoryEveryOnePermissions, `salePrice` AS salePrice, `saleType` AS saleType, `creationDate` AS creationDate, `groupID` AS groupID, `groupOwned` AS groupOwned, `flags` AS flags, `UUID` AS inventoryID, `parentFolderID` AS parentFolderID, `avatarID` AS avatarID, `inventoryGroupPermissions` AS inventoryGroupPermissions FROM old.inventoryitems;
COMMIT;

View file

@ -1,57 +0,0 @@
/*
* 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.Data.SQLite;
namespace OpenSim.Data.SQLite
{
public class SQLiteAgentPreferencesData : SQLiteGenericTableHandler<AgentPreferencesData>, IAgentPreferencesData
{
public SQLiteAgentPreferencesData(string connectionString, string realm)
: base(connectionString, realm, "AgentPrefs")
{
}
public AgentPreferencesData GetPrefs(UUID agentID)
{
AgentPreferencesData[] ret = Get("PrincipalID", agentID.ToString());
if (ret.Length == 0)
return null;
return ret[0];
}
}
}

View file

@ -1,404 +0,0 @@
/*
* 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.Data;
using System.Reflection;
using System.Data.SQLite;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenMetaverse;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// An asset storage interface for the SQLite database system
/// </summary>
public class SQLiteAssetData : AssetDataBase
{
private static ILogger m_logger;
private const string SelectAssetSQL = "select * from assets where UUID=:UUID";
private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, asset_flags, UUID, CreatorID from assets limit :start, :count";
private const string DeleteAssetSQL = "delete from assets where UUID=:UUID";
private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, asset_flags, CreatorID, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Flags, :CreatorID, :Data)";
private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, asset_flags=:Flags, CreatorID=:CreatorID, Data=:Data where UUID=:UUID";
private const string assetSelect = "select * from assets";
private SQLiteConnection m_conn;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
override public void Dispose()
{
if (m_conn != null)
{
m_conn.Close();
m_conn = null;
}
}
/// <summary>
/// <list type="bullet">
/// <item>Initialises AssetData interface</item>
/// <item>Loads and initialises a new SQLite connection and maintains it.</item>
/// <item>use default URI if connect string is empty.</item>
/// </list>
/// </summary>
/// <param name="dbconnect">connect string</param>
override public void Initialise(string dbconnect)
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<SQLiteAssetData>>();
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
if (dbconnect.Length == 0)
{
dbconnect = "URI=file:Asset.db,version=3";
}
m_conn = new SQLiteConnection(dbconnect);
m_conn.Open();
Migration m = new Migration(m_conn, Assembly, "AssetStore");
m.Update();
return;
}
/// <summary>
/// Fetch Asset
/// </summary>
/// <param name="uuid">UUID of ... ?</param>
/// <returns>Asset base</returns>
override public AssetBase GetAsset(UUID uuid)
{
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(SelectAssetSQL, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":UUID", uuid.ToString()));
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
AssetBase asset = buildAsset(reader);
reader.Close();
return asset;
}
else
{
reader.Close();
return null;
}
}
}
}
}
/// <summary>
/// Create an asset
/// </summary>
/// <param name="asset">Asset Base</param>
override public bool StoreAsset(AssetBase asset)
{
string assetName = asset.Name;
if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
{
assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
m_logger.LogWarning(
"[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 > AssetBase.MAX_ASSET_DESC)
{
assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
m_logger.LogWarning(
"[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
//m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString());
if (AssetsExist(new[] { asset.FullID })[0])
{
//LogAssetLoad(asset);
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(UpdateAssetSQL, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":Name", assetName));
cmd.Parameters.Add(new SQLiteParameter(":Description", assetDescription));
cmd.Parameters.Add(new SQLiteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SQLiteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SQLiteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SQLiteParameter(":Flags", asset.Flags));
cmd.Parameters.Add(new SQLiteParameter(":CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(new SQLiteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
return true;
}
}
}
else
{
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(InsertAssetSQL, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":Name", assetName));
cmd.Parameters.Add(new SQLiteParameter(":Description", assetDescription));
cmd.Parameters.Add(new SQLiteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SQLiteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SQLiteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SQLiteParameter(":Flags", asset.Flags));
cmd.Parameters.Add(new SQLiteParameter(":CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(new SQLiteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
return true;
}
}
}
}
// /// <summary>
// /// Some... logging functionnality
// /// </summary>
// /// <param name="asset"></param>
// private static void LogAssetLoad(AssetBase asset)
// {
// string temporary = asset.Temporary ? "Temporary" : "Stored";
// string local = asset.Local ? "Local" : "Remote";
//
// int assetLength = (asset.Data != null) ? asset.Data.Length : 0;
//
// m_log.Debug("[ASSET DB]: " +
// string.Format("Loaded {5} {4} Asset: [{0}][{3}] \"{1}\":{2} ({6} bytes)",
// asset.FullID, asset.Name, asset.Description, asset.Type,
// temporary, local, assetLength));
// }
/// <summary>
/// Check if the assets exist in the database.
/// </summary>
/// <param name="uuids">The assets' IDs</param>
/// <returns>For each asset: true if it exists, false otherwise</returns>
public override bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return new bool[0];
HashSet<UUID> exist = new HashSet<UUID>();
string ids = "'" + string.Join("','", uuids) + "'";
string sql = string.Format("select UUID from assets where UUID in ({0})", ids);
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(sql, m_conn))
{
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
UUID id = new UUID((string)reader["UUID"]);
exist.Add(id);
}
}
}
}
bool[] results = new bool[uuids.Length];
for (int i = 0; i < uuids.Length; i++)
results[i] = exist.Contains(uuids[i]);
return results;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
private static AssetBase buildAsset(IDataReader row)
{
// TODO: this doesn't work yet because something more
// interesting has to be done to actually get these values
// back out. Not enough time to figure it out yet.
AssetBase asset = new AssetBase(
new UUID((String)row["UUID"]),
(String)row["Name"],
Convert.ToSByte(row["Type"]),
(String)row["CreatorID"]
);
asset.Description = (String) row["Description"];
asset.Local = Convert.ToBoolean(row["Local"]);
asset.Temporary = Convert.ToBoolean(row["Temporary"]);
asset.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]);
asset.Data = (byte[])row["Data"];
return asset;
}
private static AssetMetadata buildAssetMetadata(IDataReader row)
{
AssetMetadata metadata = new AssetMetadata();
metadata.FullID = new UUID((string) row["UUID"]);
metadata.Name = (string) row["Name"];
metadata.Description = (string) row["Description"];
metadata.Type = Convert.ToSByte(row["Type"]);
metadata.Temporary = Convert.ToBoolean(row["Temporary"]); // Not sure if this is correct.
metadata.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]);
metadata.CreatorID = row["CreatorID"].ToString();
// Current SHA1s are not stored/computed.
metadata.SHA1 = Array.Empty<byte>();
return metadata;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(SelectAssetMetadataSQL, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":start", start));
cmd.Parameters.Add(new SQLiteParameter(":count", count));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
AssetMetadata metadata = buildAssetMetadata(reader);
retList.Add(metadata);
}
}
}
}
return retList;
}
/***********************************************************************
*
* Database Binding functions
*
* These will be db specific due to typing, and minor differences
* in databases.
*
**********************************************************************/
#region IPlugin interface
/// <summary>
///
/// </summary>
override public string Version
{
get
{
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);
}
}
/// <summary>
/// Initialise the AssetData interface using default URI
/// </summary>
override public void Initialise()
{
Initialise("URI=file:Asset.db,version=3");
}
/// <summary>
/// Name of this DB provider
/// </summary>
override public string Name
{
get { return "SQLite Asset storage engine"; }
}
// TODO: (AlexRa): one of these is to be removed eventually (?)
/// <summary>
/// Delete an asset from database
/// </summary>
/// <param name="uuid"></param>
public bool DeleteAsset(UUID uuid)
{
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(DeleteAssetSQL, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":UUID", uuid.ToString()));
cmd.ExecuteNonQuery();
}
}
return true;
}
public override bool Delete(string id)
{
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return false;
return DeleteAsset(assetID);
}
#endregion
}
}

View file

@ -1,253 +0,0 @@
/*
* 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.Data;
using System.Data.SQLite;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenMetaverse;
using OpenSim.Server.Base;
namespace OpenSim.Data.SQLite
{
public class SQLiteAuthenticationData : SQLiteFramework, IAuthenticationData
{
private static ILogger m_logger;
private string m_Realm;
private List<string> m_ColumnNames;
private int m_LastExpire;
protected static SQLiteConnection m_Connection;
private static bool m_initialized = false;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public SQLiteAuthenticationData(string connectionString, string realm)
: base(connectionString)
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<SQLiteAuthenticationData>>();
m_Realm = realm;
if (!m_initialized)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
m_Connection = new SQLiteConnection(connectionString);
m_Connection.Open();
Migration m = new Migration(m_Connection, Assembly, "AuthStore");
m.Update();
m_initialized = true;
}
}
public AuthenticationData Get(UUID principalID)
{
AuthenticationData ret = new AuthenticationData();
ret.Data = new Dictionary<string, object>();
IDataReader result;
using (SQLiteCommand cmd = new SQLiteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID"))
{
cmd.Parameters.Add(new SQLiteParameter(":PrincipalID", principalID.ToString()));
result = ExecuteReader(cmd, m_Connection);
}
try
{
if (result.Read())
{
ret.PrincipalID = principalID;
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
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;
ret.Data[s] = result[s].ToString();
}
return ret;
}
else
{
return null;
}
}
catch
{
}
return null;
}
public bool Store(AuthenticationData data)
{
if (data.Data.ContainsKey("UUID"))
data.Data.Remove("UUID");
string[] fields = new List<string>(data.Data.Keys).ToArray();
string[] values = new string[data.Data.Count];
int i = 0;
foreach (object o in data.Data.Values)
values[i++] = o.ToString();
using (SQLiteCommand cmd = new SQLiteCommand())
{
if (Get(data.PrincipalID) != null)
{
string update = "update `" + m_Realm + "` set ";
bool first = true;
foreach (string field in fields)
{
if (!first)
update += ", ";
update += "`" + field + "` = :" + field;
cmd.Parameters.Add(new SQLiteParameter(":" + field, data.Data[field]));
first = false;
}
update += " where UUID = :UUID";
cmd.Parameters.Add(new SQLiteParameter(":UUID", data.PrincipalID.ToString()));
cmd.CommandText = update;
try
{
if (ExecuteNonQuery(cmd, m_Connection) < 1)
{
//CloseCommand(cmd);
return false;
}
}
catch (Exception e)
{
m_logger.LogError("[SQLITE]: Exception storing authentication data", e);
//CloseCommand(cmd);
return false;
}
}
else
{
string insert = "insert into `" + m_Realm + "` (`UUID`, `" +
String.Join("`, `", fields) +
"`) values (:UUID, :" + String.Join(", :", fields) + ")";
cmd.Parameters.Add(new SQLiteParameter(":UUID", data.PrincipalID.ToString()));
foreach (string field in fields)
cmd.Parameters.Add(new SQLiteParameter(":" + field, data.Data[field]));
cmd.CommandText = insert;
try
{
if (ExecuteNonQuery(cmd, m_Connection) < 1)
{
return false;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
}
}
return true;
}
public bool SetDataItem(UUID principalID, string item, string value)
{
using (SQLiteCommand cmd = new SQLiteCommand("update `" + m_Realm +
"` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'"))
{
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
}
return false;
}
public bool SetToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
using (SQLiteCommand cmd = new SQLiteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() +
"', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))"))
{
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
}
return false;
}
public bool CheckToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
using (SQLiteCommand cmd = new SQLiteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() +
" minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')"))
{
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
}
return false;
}
private void DoExpire()
{
using (SQLiteCommand cmd = new SQLiteCommand("delete from tokens where validity < datetime('now', 'localtime')"))
ExecuteNonQuery(cmd, m_Connection);
m_LastExpire = System.Environment.TickCount;
}
}
}

View file

@ -1,63 +0,0 @@
/*
* 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.Data.SQLite;
using OpenMetaverse;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// A SQLite Interface for Avatar Data
/// </summary>
public class SQLiteAvatarData : SQLiteGenericTableHandler<AvatarBaseData>,
IAvatarData
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public SQLiteAvatarData(string connectionString, string realm) :
base(connectionString, realm, "Avatar")
{
}
public bool Delete(UUID principalID, string name)
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.CommandText = String.Format("delete from {0} where `PrincipalID` = :PrincipalID and `Name` = :Name", m_Realm);
cmd.Parameters.AddWithValue(":PrincipalID", principalID.ToString());
cmd.Parameters.AddWithValue(":Name", name);
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
}
return false;
}
}
}

View file

@ -1,512 +0,0 @@
/*
* 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.Data;
using System.Data.SQLite;
using System.Reflection;
using OpenSim.Framework;
using OpenMetaverse;
using OpenSim.Server.Base;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace OpenSim.Data.SQLite
{
public class SQLiteEstateStore : IEstateDataStore
{
private static ILogger m_logger;
private SQLiteConnection m_connection;
private string m_connectionString;
private FieldInfo[] m_Fields;
private Dictionary<string, FieldInfo> m_FieldMap =
new Dictionary<string, FieldInfo>();
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public SQLiteEstateStore()
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<SQLiteEstateStore>>();
}
public SQLiteEstateStore(string connectionString)
{
Initialise(connectionString);
}
public void Initialise(string connectionString)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
m_connectionString = connectionString;
m_logger.LogInformation("[ESTATE DB]: Sqlite - connecting: "+m_connectionString);
m_connection = new SQLiteConnection(m_connectionString);
m_connection.Open();
Migration m = new Migration(m_connection, Assembly, "EstateStore");
m.Update();
//m_connection.Close();
// m_connection.Open();
Type t = typeof(EstateSettings);
m_Fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo f in m_Fields)
if (f.Name.Substring(0, 2) == "m_")
m_FieldMap[f.Name.Substring(2)] = f;
}
private string[] FieldList
{
get { return new List<string>(m_FieldMap.Keys).ToArray(); }
}
public EstateSettings LoadEstateSettings(UUID regionID, bool create)
{
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";
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
return DoLoad(cmd, regionID, create);
}
}
private EstateSettings DoLoad(SQLiteCommand cmd, UUID regionID, bool create)
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
IDataReader r = null;
try
{
r = cmd.ExecuteReader();
}
catch (SQLiteException)
{
m_logger.LogError("[SQLITE]: There was an issue loading the estate settings. This can happen the first time running OpenSimulator with CSharpSqlite the first time. OpenSimulator will probably crash, restart it and it should be good to go.");
}
if (r != null && r.Read())
{
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
int v = Convert.ToInt32(r[name]);
if (v != 0)
m_FieldMap[name].SetValue(es, true);
else
m_FieldMap[name].SetValue(es, false);
}
else if (m_FieldMap[name].GetValue(es) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(r[name].ToString(), out uuid);
m_FieldMap[name].SetValue(es, uuid);
}
else
{
m_FieldMap[name].SetValue(es, Convert.ChangeType(r[name], m_FieldMap[name].FieldType));
}
}
r.Close();
}
else if (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");
return es;
}
public EstateSettings CreateNewEstate(int estateID)
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
es.EstateID = Convert.ToUInt32(estateID);
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<string> names = new List<string>(FieldList);
using (SQLiteCommand cmd = m_connection.CreateCommand())
{
if (es.EstateID < 100)
{
cmd.CommandText = "select MAX(EstateID) FROM estate_settings";
cmd.Parameters.Clear();
uint a = 0;
object r = cmd.ExecuteScalar();
if(r!=null && !(r is DBNull))
{
a = Convert.ToUInt32(r);
}
if (a < 100)
a = 100;
++a;
es.EstateID = a;
}
cmd.CommandText = "insert into estate_settings ("+String.Join(",", names.ToArray())+") values ( :"+String.Join(", :", names.ToArray())+")";
cmd.Parameters.Clear();
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue(":"+name, "1");
else
cmd.Parameters.AddWithValue(":"+name, "0");
}
else
{
cmd.Parameters.AddWithValue(":"+name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
}
}
public void StoreEstateSettings(EstateSettings es)
{
List<string> fields = new List<string>(FieldList);
fields.Remove("EstateID");
List<string> terms = new List<string>();
foreach (string f in fields)
terms.Add(f+" = :"+f);
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "update estate_settings set " + String.Join(", ", terms.ToArray()) + " where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID);
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue(":"+name, "1");
else
cmd.Parameters.AddWithValue(":"+name, "0");
}
else
{
cmd.Parameters.AddWithValue(":"+name, m_FieldMap[name].GetValue(es).ToString());
}
}
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);
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
IDataReader r;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "select * from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID);
r = cmd.ExecuteReader();
}
while (r.Read())
{
EstateBan eb = new EstateBan();
eb.BannedUserID = DBGuid.FromDB(r["bannedUUID"]);
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
eb.BanningUserID = DBGuid.FromDB(r["banningUUID"]);
eb.BanTime = Convert.ToInt32(r["banTime"]);
es.AddBan(eb);
}
r.Close();
}
private void SaveBanList(EstateSettings es)
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "delete from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask, banningUUID, banTime) values ( :EstateID, :bannedUUID, '', '', '', :banningUUID, :banTime )";
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue(":bannedUUID", b.BannedUserID.ToString());
cmd.Parameters.AddWithValue(":banningUUID", b.BanningUserID.ToString());
cmd.Parameters.AddWithValue(":banTime", b.BanTime);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
}
void SaveUUIDList(uint EstateID, string table, UUID[] data)
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "delete from "+table+" where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into "+table+" (EstateID, uuid) values ( :EstateID, :uuid )";
foreach (UUID uuid in data)
{
cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString());
cmd.Parameters.AddWithValue(":uuid", uuid.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
}
UUID[] LoadUUIDList(uint EstateID, string table)
{
List<UUID> uuids = new List<UUID>();
IDataReader r;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "select uuid from "+table+" where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", EstateID);
r = cmd.ExecuteReader();
}
while (r.Read())
{
// EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["uuid"].ToString(), out uuid);
uuids.Add(uuid);
}
r.Close();
return uuids.ToArray();
}
public EstateSettings LoadEstateSettings(int estateID)
{
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID = :EstateID";
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateID", estateID.ToString());
return DoLoad(cmd, UUID.Zero, false);
}
}
public List<EstateSettings> LoadEstateSettingsAll()
{
List<EstateSettings> estateSettings = new List<EstateSettings>();
List<int> estateIds = GetEstatesAll();
foreach (int estateId in estateIds)
estateSettings.Add(LoadEstateSettings(estateId));
return estateSettings;
}
public List<int> GetEstates(string search)
{
List<int> result = new List<int>();
string sql = "select EstateID from estate_settings where estate_settings.EstateName = :EstateName";
IDataReader r;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateName", search);
r = cmd.ExecuteReader();
}
while (r.Read())
{
result.Add(Convert.ToInt32(r["EstateID"]));
}
r.Close();
return result;
}
public List<int> GetEstatesAll()
{
List<int> result = new List<int>();
string sql = "select EstateID from estate_settings";
IDataReader r;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = sql;
r = cmd.ExecuteReader();
}
while (r.Read())
{
result.Add(Convert.ToInt32(r["EstateID"]));
}
r.Close();
return result;
}
public List<int> GetEstatesByOwner(UUID ownerID)
{
List<int> result = new List<int>();
string sql = "select EstateID from estate_settings where estate_settings.EstateOwner = :EstateOwner";
IDataReader r;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateOwner", ownerID);
r = cmd.ExecuteReader();
}
while (r.Read())
{
result.Add(Convert.ToInt32(r["EstateID"]));
}
r.Close();
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
using(SQLiteTransaction transaction = m_connection.BeginTransaction())
{
// Delete any existing estate mapping for this region.
using(SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "delete from estate_map where RegionID = :RegionID";
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
cmd.ExecuteNonQuery();
}
using(SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
cmd.Parameters.AddWithValue(":EstateID", estateID.ToString());
if (cmd.ExecuteNonQuery() == 0)
{
transaction.Rollback();
return false;
}
else
{
transaction.Commit();
return true;
}
}
}
}
public List<UUID> GetRegions(int estateID)
{
return new List<UUID>();
}
public bool DeleteEstate(int estateID)
{
return false;
}
}
}

View file

@ -1,89 +0,0 @@
/*
* 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.Data.SQLite;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// A database interface class to a user profile storage system
/// </summary>
public class SQLiteFramework
{
protected Object m_lockObject = new Object();
protected SQLiteFramework(string connectionString)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
}
//////////////////////////////////////////////////////////////
//
// All non queries are funneled through one connection
// to increase performance a little
//
protected int ExecuteNonQuery(SQLiteCommand cmd, SQLiteConnection connection)
{
lock (connection)
{
/*
SQLiteConnection newConnection =
(SQLiteConnection)((ICloneable)connection).Clone();
newConnection.Open();
cmd.Connection = newConnection;
*/
cmd.Connection = connection;
//Console.WriteLine("XXX " + cmd.CommandText);
return cmd.ExecuteNonQuery();
}
}
protected IDataReader ExecuteReader(SQLiteCommand cmd, SQLiteConnection connection)
{
lock (connection)
{
//SQLiteConnection newConnection =
// (SQLiteConnection)((ICloneable)connection).Clone();
//newConnection.Open();
//cmd.Connection = newConnection;
cmd.Connection = connection;
//Console.WriteLine("XXX " + cmd.CommandText);
return cmd.ExecuteReader();
}
}
}
}

View file

@ -1,82 +0,0 @@
/*
* 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.Data.SQLite;
namespace OpenSim.Data.SQLite
{
public class SQLiteFriendsData : SQLiteGenericTableHandler<FriendsData>, IFriendsData
{
public SQLiteFriendsData(string connectionString, string realm)
: base(connectionString, realm, "FriendsStore")
{
}
public FriendsData[] GetFriends(UUID principalID)
{
return GetFriends(principalID.ToString());
}
public FriendsData[] GetFriends(string userID)
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
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.AddWithValue(":PrincipalID", userID.ToString());
return DoQuery(cmd);
}
}
public bool Delete(UUID principalID, string friend)
{
return Delete(principalID.ToString(), friend);
}
public override bool Delete(string principalID, string friend)
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.CommandText = String.Format("delete from {0} where PrincipalID = :PrincipalID and Friend = :Friend", m_Realm);
cmd.Parameters.AddWithValue(":PrincipalID", principalID.ToString());
cmd.Parameters.AddWithValue(":Friend", friend);
ExecuteNonQuery(cmd, m_Connection);
}
return true;
}
}
}

View file

@ -1,290 +0,0 @@
/*
* 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.Data;
using System.Data.SQLite;
using System.Reflection;
using OpenMetaverse;
namespace OpenSim.Data.SQLite
{
public class SQLiteGenericTableHandler<T> : SQLiteFramework where T: class, new()
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
protected static SQLiteConnection m_Connection;
private static bool m_initialized;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public SQLiteGenericTableHandler(string connectionString,
string realm, string storeName) : base(connectionString)
{
m_Realm = realm;
if (!m_initialized)
{
m_Connection = new SQLiteConnection(connectionString);
//Console.WriteLine(string.Format("OPENING CONNECTION FOR {0} USING {1}", storeName, connectionString));
m_Connection.Open();
if (storeName != String.Empty)
{
//SQLiteConnection newConnection =
// (SQLiteConnection)((ICloneable)m_Connection).Clone();
//newConnection.Open();
//Migration m = new Migration(newConnection, Assembly, storeName);
Migration m = new Migration(m_Connection, Assembly, storeName);
m.Update();
//newConnection.Close();
//newConnection.Dispose();
}
m_initialized = true;
}
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
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 CheckColumnNames(IDataReader reader)
{
if (m_ColumnNames != null)
return;
m_ColumnNames = new List<string>();
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());
}
}
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<string> terms = new List<string>();
using (SQLiteCommand cmd = new SQLiteCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.Add(new SQLiteParameter(":" + 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.CommandText = query;
return DoQuery(cmd);
}
}
protected T[] DoQuery(SQLiteCommand cmd)
{
IDataReader reader = ExecuteReader(cmd, m_Connection);
if (reader == null)
return new T[0];
CheckColumnNames(reader);
List<T> result = new List<T>();
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<string, string> data =
new Dictionary<string, string>();
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);
}
//CloseCommand(cmd);
return result.ToArray();
}
public virtual T[] Get(string where)
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
}
public virtual bool Store(T row)
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
string query = "";
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add(":" + fi.Name);
cmd.Parameters.Add(new SQLiteParameter(":" + fi.Name, fi.GetValue(row).ToString()));
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
names.Add(kvp.Key);
values.Add(":" + kvp.Key);
cmd.Parameters.Add(new SQLiteParameter(":" + kvp.Key, kvp.Value));
}
}
query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
cmd.CommandText = query;
if (ExecuteNonQuery(cmd, m_Connection) > 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<string> terms = new List<string>();
using (SQLiteCommand cmd = new SQLiteCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.Add(new SQLiteParameter(":" + 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.CommandText = query;
return ExecuteNonQuery(cmd, m_Connection) > 0;
}
}
}
}

View file

@ -1,56 +0,0 @@
/*
* 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.
*/
namespace OpenSim.Data.SQLite
{
/// <summary>
/// A SQL Interface for user grid data
/// </summary>
public class SQLiteGridUserData : SQLiteGenericTableHandler<GridUserData>, IGridUserData
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public SQLiteGridUserData(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));
}
}
}

View file

@ -1,76 +0,0 @@
/*
* 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.Data.SQLite;
using OpenMetaverse;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// A SQL Interface for user grid data
/// </summary>
public class SQLiteHGTravelData : SQLiteGenericTableHandler<HGTravelingData>, IHGTravelingData
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public SQLiteHGTravelData(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 (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.CommandText = String.Format("delete from {0} where TMStamp < datetime('now', '-2 day') ", m_Realm);
DoQuery(cmd);
}
}
}
}

View file

@ -1,68 +0,0 @@
/*
* 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.Data.SQLite;
namespace OpenSim.Data.SQLite
{
public class SQLiteMuteListData : SQLiteGenericTableHandler<MuteData>, IMuteListData
{
public SQLiteMuteListData(string connectionString)
: base(connectionString, "MuteList", "MuteListStore")
{
}
public MuteData[] Get(UUID agentID)
{
MuteData[] data = base.Get("AgentID", agentID.ToString());
return data;
}
public bool Delete(UUID agentID, UUID muteID, string muteName)
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.CommandText = "delete from MuteList where `AgentID` = :AgentID and `MuteID` = :MuteID and `MuteName` = :MuteName";
cmd.Parameters.AddWithValue(":AgentID", agentID.ToString());
cmd.Parameters.AddWithValue(":MuteID", muteID.ToString());
cmd.Parameters.AddWithValue(":MuteName", muteName);
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
return false;
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,87 +0,0 @@
/*
* 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.Data.SQLite;
namespace OpenSim.Data.SQLite
{
public class SQLiteUserAccountData : SQLiteGenericTableHandler<UserAccountData>, IUserAccountData
{
public SQLiteUserAccountData(string connectionString, string realm)
: base(connectionString, realm, "UserAccount")
{
}
public UserAccountData[] GetUsers(UUID scopeID, string query)
{
string[] words = query.Split();
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];
using (SQLiteCommand cmd = new SQLiteCommand())
{
if (words.Length == 1)
{
cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{2}%')",
m_Realm, scopeID.ToString(), words[0]);
}
else
{
cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{3}%')",
m_Realm, scopeID.ToString(), words[0], words[1]);
}
return DoQuery(cmd);
}
}
public UserAccountData[] GetUsersWhere(UUID scopeID, string where)
{
return null;
}
}
}

View file

@ -1,977 +0,0 @@
/*
* 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.Data;
using System.Reflection;
using System.Data.SQLite;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenSim.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Server.Base;
namespace OpenSim.Data.SQLite
{
public class SQLiteUserProfilesData: IProfilesData
{
private static ILogger m_logger;
private SQLiteConnection m_connection;
private string m_connectionString;
private Dictionary<string, FieldInfo> m_FieldMap =
new Dictionary<string, FieldInfo>();
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public SQLiteUserProfilesData()
{
m_logger ??= OpenSimServer.Instance.ServiceProvider.GetRequiredService<ILogger<SQLiteUserProfilesData>>();
}
public void Initialize(string connectionString)
{
base.Initialize(connectionString);
}
public void Initialise(string connectionString)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
m_connectionString = connectionString;
m_logger?.LogInformation("[PROFILES_DATA]: Sqlite - connecting: "+m_connectionString);
m_connection = new SQLiteConnection(m_connectionString);
m_connection.Open();
Migration m = new Migration(m_connection, Assembly, "UserProfiles");
m.Update();
}
private string[] FieldList
{
get { return new List<string>(m_FieldMap.Keys).ToArray(); }
}
#region IProfilesData implementation
public OSDArray GetClassifiedRecords(UUID creatorId)
{
OSDArray data = new OSDArray();
string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = :Id";
IDataReader reader = null;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", creatorId);
reader = cmd.ExecuteReader();
}
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_logger?.LogError("[PROFILES_DATA]" +
": UserAccount exception {0}", e.Message);
}
n.Add("classifieduuid", OSD.FromUUID(Id));
n.Add("name", OSD.FromString(Name));
data.Add(n);
}
reader.Close();
return data;
}
public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result)
{
string query = string.Empty;
query += "INSERT OR REPLACE INTO classifieds (";
query += "`classifieduuid`,";
query += "`creatoruuid`,";
query += "`creationdate`,";
query += "`expirationdate`,";
query += "`category`,";
query += "`name`,";
query += "`description`,";
query += "`parceluuid`,";
query += "`parentestate`,";
query += "`snapshotuuid`,";
query += "`simname`,";
query += "`posglobal`,";
query += "`parcelname`,";
query += "`classifiedflags`,";
query += "`priceforlisting`) ";
query += "VALUES (";
query += ":ClassifiedId,";
query += ":CreatorId,";
query += ":CreatedDate,";
query += ":ExpirationDate,";
query += ":Category,";
query += ":Name,";
query += ":Description,";
query += ":ParcelId,";
query += ":ParentEstate,";
query += ":SnapshotId,";
query += ":SimName,";
query += ":GlobalPos,";
query += ":ParcelName,";
query += ":Flags,";
query += ":ListingPrice ) ";
if(string.IsNullOrEmpty(ad.ParcelName))
ad.ParcelName = "Unknown";
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 (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
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_logger?.LogError("[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 ";
query += "classifieduuid = :ClasifiedId";
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ClassifiedId", recordId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_logger?.LogError("[PROFILES_DATA]" +
": DeleteClassifiedRecord exception {0}", e.Message);
return false;
}
return true;
}
public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT * FROM classifieds WHERE ";
query += "classifieduuid = :AdId";
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":AdId", ad.ClassifiedId.ToString());
using (reader = cmd.ExecuteReader())
{
if(reader.Read ())
{
ad.CreatorId = new UUID(reader["creatoruuid"].ToString());
ad.ParcelId = new UUID(reader["parceluuid"].ToString ());
ad.SnapshotId = new UUID(reader["snapshotuuid"].ToString ());
ad.CreationDate = Convert.ToInt32(reader["creationdate"]);
ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]);
ad.ParentEstate = Convert.ToInt32(reader["parentestate"]);
ad.Flags = (byte) Convert.ToUInt32(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();
}
}
}
}
catch (Exception e)
{
m_logger?.LogError("[PROFILES_DATA]" +
": GetPickInfo exception {0}", e.Message);
}
return true;
}
public OSDArray GetAvatarPicks(UUID avatarId)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT `pickuuid`,`name` FROM userpicks WHERE ";
query += "creatoruuid = :Id";
OSDArray data = new OSDArray();
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader())
{
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_logger?.LogError("[PROFILES_DATA]" +
": GetAvatarPicks exception {0}", e.Message);
}
return data;
}
public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId)
{
IDataReader reader = null;
string query = string.Empty;
UserProfilePick pick = new UserProfilePick();
query += "SELECT * FROM userpicks WHERE ";
query += "creatoruuid = :CreatorId AND ";
query += "pickuuid = :PickId";
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":CreatorId", avatarId.ToString());
cmd.Parameters.AddWithValue(":PickId", pickId.ToString());
using (reader = cmd.ExecuteReader())
{
while (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"].ToString(), out pick.TopPick);
bool.TryParse((string)reader["enabled"].ToString(), out pick.Enabled);
pick.Name = (string)reader["name"];
pick.Desc = description;
pick.ParcelName = (string)reader["user"];
pick.OriginalName = (string)reader["originalname"];
pick.SimName = (string)reader["simname"];
pick.SortOrder = (int)reader["sortorder"];
}
}
}
}
catch (Exception e)
{
m_logger?.LogError("[PROFILES_DATA]" +
": GetPickInfo exception {0}", e.Message);
}
return pick;
}
public bool UpdatePicksRecord(UserProfilePick pick)
{
string query = string.Empty;
query += "INSERT OR REPLACE INTO userpicks (";
query += "pickuuid, ";
query += "creatoruuid, ";
query += "toppick, ";
query += "parceluuid, ";
query += "name, ";
query += "description, ";
query += "snapshotuuid, ";
query += "user, ";
query += "originalname, ";
query += "simname, ";
query += "posglobal, ";
query += "sortorder, ";
query += "enabled ) ";
query += "VALUES (";
query += ":PickId,";
query += ":CreatorId,";
query += ":TopPick,";
query += ":ParcelId,";
query += ":Name,";
query += ":Desc,";
query += ":SnapshotId,";
query += ":User,";
query += ":Original,";
query += ":SimName,";
query += ":GlobalPos,";
query += ":SortOrder,";
query += ":Enabled) ";
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
int top_pick;
int.TryParse(pick.TopPick.ToString(), out top_pick);
int enabled;
int.TryParse(pick.Enabled.ToString(), out enabled);
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":PickId", pick.PickId.ToString());
cmd.Parameters.AddWithValue(":CreatorId", pick.CreatorId.ToString());
cmd.Parameters.AddWithValue(":TopPick", top_pick);
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.ParcelName.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", enabled);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_logger?.LogError("[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 (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":PickId", pickId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_logger?.LogError("[PROFILES_DATA]" +
": DeleteUserPickRecord exception {0}", e.Message);
return false;
}
return true;
}
public bool GetAvatarNotes(ref UserProfileNotes notes)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT `notes` FROM usernotes WHERE ";
query += "useruuid = :Id AND ";
query += "targetuuid = :TargetId";
OSDArray data = new OSDArray();
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", notes.UserId.ToString());
cmd.Parameters.AddWithValue(":TargetId", notes.TargetId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
while (reader.Read())
{
notes.Notes = OSD.FromString((string)reader["notes"]);
}
}
}
}
catch (Exception e)
{
m_logger?.LogError("[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 OR REPLACE INTO usernotes VALUES ( ";
query += ":UserId,";
query += ":TargetId,";
query += ":Notes )";
}
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
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_logger?.LogError("[PROFILES_DATA]" +
": UpdateAvatarNotes exception {0}", e.Message);
return false;
}
return true;
}
public bool GetAvatarProperties(ref UserProfileProperties props, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT * FROM userprofile WHERE ";
query += "useruuid = :Id";
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", props.UserId.ToString());
try
{
reader = cmd.ExecuteReader();
}
catch(Exception e)
{
m_logger?.LogError("[PROFILES_DATA]" +
": GetAvatarProperties exception {0}", e.Message);
result = e.Message;
return false;
}
if(reader != null && 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
{
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)";
using (SQLiteCommand put = (SQLiteCommand)m_connection.CreateCommand())
{
put.CommandText = query;
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();
}
}
}
return true;
}
public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result)
{
string query = string.Empty;
query += "UPDATE userprofile SET ";
query += "profileURL=:profileURL, ";
query += "profileImage=:image, ";
query += "profileAboutText=:abouttext,";
query += "profileFirstImage=:firstlifeimage,";
query += "profileFirstText=:firstlifetext ";
query += "WHERE useruuid=:uuid";
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":profileURL", props.WebUrl);
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_logger?.LogError("[PROFILES_DATA]" +
": AgentPropertiesUpdate exception {0}", e.Message);
return false;
}
return true;
}
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 (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
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_logger?.LogError("[PROFILES_DATA]" +
": AgentInterestsUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool UpdateUserPreferences(ref UserPreferences pref, ref string result)
{
string query = string.Empty;
query += "UPDATE usersettings SET ";
query += "imviaemail=:ImViaEmail, ";
query += "visible=:Visible, ";
query += "email=:EMail ";
query += "WHERE useruuid=:uuid";
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ImViaEmail", pref.IMViaEmail);
cmd.Parameters.AddWithValue(":Visible", pref.Visible);
cmd.Parameters.AddWithValue(":EMail", pref.EMail);
cmd.Parameters.AddWithValue(":uuid", pref.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_logger?.LogError("[PROFILES_DATA]" +
": AgentInterestsUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool GetUserPreferences(ref UserPreferences pref, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT imviaemail,visible,email FROM ";
query += "usersettings WHERE ";
query += "useruuid = :Id";
OSDArray data = new OSDArray();
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue("?Id", pref.UserId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
bool.TryParse((string)reader["imviaemail"], out pref.IMViaEmail);
bool.TryParse((string)reader["visible"], out pref.Visible);
pref.EMail = (string)reader["email"];
}
else
{
query = "INSERT INTO usersettings VALUES ";
query += "(:Id,'false','false', :Email)";
using (SQLiteCommand put = (SQLiteCommand)m_connection.CreateCommand())
{
put.Parameters.AddWithValue(":Id", pref.UserId.ToString());
put.Parameters.AddWithValue(":Email", pref.EMail);
put.ExecuteNonQuery();
}
}
}
}
}
catch (Exception e)
{
m_logger?.LogError("[PROFILES_DATA]" +
": Get preferences exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool GetUserAppData(ref UserAppData props, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT * FROM `userdata` WHERE ";
query += "UserId = :Id AND ";
query += "TagId = :TagId";
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", props.UserId.ToString());
cmd.Parameters.AddWithValue (":TagId", props.TagId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(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 (SQLiteCommand put = (SQLiteCommand)m_connection.CreateCommand())
{
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());
put.ExecuteNonQuery();
}
}
}
}
}
catch (Exception e)
{
m_logger?.LogError("[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 (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
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 ());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_logger?.LogError("[PROFILES_DATA]" +
": SetUserData exception {0}", e.Message);
return false;
}
return true;
}
public OSDArray GetUserImageAssets(UUID avatarId)
{
IDataReader reader = null;
OSDArray data = new OSDArray();
string query = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = :Id";
// Get classified image assets
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = string.Format(query, "\"classifieds\"");
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
while(reader.Read())
{
data.Add(new OSDString((string)reader["snapshotuuid"].ToString()));
}
}
}
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = string.Format(query, "\"userpicks\"");
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
data.Add(new OSDString((string)reader["snapshotuuid"].ToString ()));
}
}
}
query = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = :Id";
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
data.Add(new OSDString((string)reader["profileImage"].ToString ()));
data.Add(new OSDString((string)reader["profileFirstImage"].ToString ()));
}
}
}
}
catch (Exception e)
{
m_logger?.LogError("[PROFILES_DATA]" +
": GetAvatarNotes exception {0}", e.Message);
}
return data;
}
#endregion
}
}

View file

@ -1,307 +0,0 @@
/*
* 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.Data.SQLite;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// A base class for methods needed by all SQLite database classes
/// </summary>
public class SQLiteUtil
{
/***********************************************************************
*
* Database Definition Helper Functions
*
* This should be db agnostic as we define them in ADO.NET terms
*
**********************************************************************/
/// <summary>
///
/// </summary>
/// <param name="dt"></param>
/// <param name="name"></param>
/// <param name="type"></param>
public static void createCol(DataTable dt, string name, Type type)
{
DataColumn col = new DataColumn(name, type);
dt.Columns.Add(col);
}
/***********************************************************************
*
* SQL Statement Creation Functions
*
* These functions create SQL statements for update, insert, and create.
* They can probably be factored later to have a db independant
* portion and a db specific portion
*
**********************************************************************/
/// <summary>
/// Create an insert command
/// </summary>
/// <param name="table">table name</param>
/// <param name="dt">data table</param>
/// <returns>the created command</returns>
/// <remarks>
/// This is subtle enough to deserve some commentary.
/// Instead of doing *lots* and *lots of hardcoded strings
/// for database definitions we'll use the fact that
/// realistically all insert statements look like "insert
/// into A(b, c) values(:b, :c) on the parameterized query
/// front. If we just have a list of b, c, etc... we can
/// generate these strings instead of typing them out.
/// </remarks>
public static SQLiteCommand createInsertCommand(string table, DataTable dt)
{
string[] cols = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
DataColumn col = dt.Columns[i];
cols[i] = col.ColumnName;
}
string sql = "insert into " + table + "(";
sql += String.Join(", ", cols);
// important, the first ':' needs to be here, the rest get added in the join
sql += ") values (:";
sql += String.Join(", :", cols);
sql += ")";
SQLiteCommand cmd = new SQLiteCommand(sql);
// this provides the binding for all our parameters, so
// much less code than it used to be
foreach (DataColumn col in dt.Columns)
{
cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
}
return cmd;
}
/// <summary>
/// create an update command
/// </summary>
/// <param name="table">table name</param>
/// <param name="pk"></param>
/// <param name="dt"></param>
/// <returns>the created command</returns>
public static SQLiteCommand createUpdateCommand(string table, string pk, DataTable dt)
{
string sql = "update " + table + " set ";
string subsql = String.Empty;
foreach (DataColumn col in dt.Columns)
{
if (subsql.Length > 0)
{
// a map function would rock so much here
subsql += ", ";
}
subsql += col.ColumnName + "= :" + col.ColumnName;
}
sql += subsql;
sql += " where " + pk;
SQLiteCommand cmd = new SQLiteCommand(sql);
// this provides the binding for all our parameters, so
// much less code than it used to be
foreach (DataColumn col in dt.Columns)
{
cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
}
return cmd;
}
/// <summary>
///
/// </summary>
/// <param name="dt">Data Table</param>
/// <returns></returns>
public static string defineTable(DataTable dt)
{
string sql = "create table " + dt.TableName + "(";
string subsql = String.Empty;
foreach (DataColumn col in dt.Columns)
{
if (subsql.Length > 0)
{
// a map function would rock so much here
subsql += ",\n";
}
subsql += col.ColumnName + " " + sqliteType(col.DataType);
if (dt.PrimaryKey.Length > 0)
{
if (col == dt.PrimaryKey[0])
{
subsql += " primary key";
}
}
}
sql += subsql;
sql += ")";
return sql;
}
/***********************************************************************
*
* Database Binding functions
*
* These will be db specific due to typing, and minor differences
* in databases.
*
**********************************************************************/
///<summary>
/// <para>
/// This is a convenience function that collapses 5 repetitive
/// lines for defining SqliteParameters to 2 parameters:
/// column name and database type.
/// </para>
///
/// <para>
/// It assumes certain conventions like :param as the param
/// name to replace in parametrized queries, and that source
/// version is always current version, both of which are fine
/// for us.
/// </para>
///</summary>
/// <param name="name"></param>
/// <param name="type"></param>
///<returns>a built sqlite parameter</returns>
public static SQLiteParameter createSqliteParameter(string name, Type type)
{
SQLiteParameter param = new SQLiteParameter();
param.ParameterName = ":" + name;
param.DbType = dbtypeFromType(type);
param.SourceColumn = name;
param.SourceVersion = DataRowVersion.Current;
return param;
}
/***********************************************************************
*
* Type conversion functions
*
**********************************************************************/
/// <summary>
/// Type conversion function
/// </summary>
/// <param name="type">a type</param>
/// <returns>a DbType</returns>
public static DbType dbtypeFromType(Type type)
{
if (type == typeof (String))
{
return DbType.String;
}
else if (type == typeof (Int32))
{
return DbType.Int32;
}
else if (type == typeof (UInt32))
{
return DbType.UInt32;
}
else if (type == typeof (Int64))
{
return DbType.Int64;
}
else if (type == typeof (UInt64))
{
return DbType.UInt64;
}
else if (type == typeof (Double))
{
return DbType.Double;
}
else if (type == typeof (Boolean))
{
return DbType.Boolean;
}
else if (type == typeof (Byte[]))
{
return DbType.Binary;
}
else
{
return DbType.String;
}
}
/// <summary>
/// </summary>
/// <param name="type">a Type</param>
/// <returns>a string</returns>
/// <remarks>this is something we'll need to implement for each db slightly differently.</remarks>
public static string sqliteType(Type type)
{
if (type == typeof (String))
{
return "varchar(255)";
}
else if (type == typeof (Int32))
{
return "integer";
}
else if (type == typeof (UInt32))
{
return "integer";
}
else if (type == typeof (Int64))
{
return "varchar(255)";
}
else if (type == typeof (UInt64))
{
return "varchar(255)";
}
else if (type == typeof (Double))
{
return "float";
}
else if (type == typeof (Boolean))
{
return "integer";
}
else if (type == typeof (Byte[]))
{
return "blob";
}
else
{
return "string";
}
}
}
}

View file

@ -1,314 +0,0 @@
/*
* 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.Data;
using System.Data.SQLite;
using OpenMetaverse;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// A SQLite Interface for the Asset Server
/// </summary>
public class SQLiteXInventoryData : IXInventoryData
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SqliteFolderHandler m_Folders;
private SqliteItemHandler m_Items;
public SQLiteXInventoryData(string conn, string realm)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
m_Folders = new SqliteFolderHandler(
conn, "inventoryfolders", "XInventoryStore");
m_Items = new SqliteItemHandler(
conn, "inventoryitems", String.Empty);
}
public XInventoryFolder[] GetFolder(string field, string val)
{
return m_Folders.Get(field, val);
}
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);
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
return m_Items.GetAssetPermissions(principalID, assetID);
}
}
public class SqliteItemHandler : SqliteInventoryHandler<XInventoryItem>
{
public SqliteItemHandler(string c, string t, string m) :
base(c, t, m)
{
}
public override bool Store(XInventoryItem item)
{
if (!base.Store(item))
return false;
IncrementFolderVersion(item.parentFolderID);
return true;
}
public override bool Delete(string field, string val)
{
XInventoryItem[] retrievedItems = Get(new string[] { field }, new string[] { val });
if (retrievedItems.Length == 0)
return false;
if (!base.Delete(field, val))
return false;
// Don't increment folder version here since Delete(string, string) calls Delete(string[], string[])
// IncrementFolderVersion(retrievedItems[0].parentFolderID);
return true;
}
public override bool Delete(string[] fields, string[] vals)
{
XInventoryItem[] retrievedItems = Get(fields, vals);
if (retrievedItems.Length == 0)
return false;
if (!base.Delete(fields, vals))
return false;
HashSet<UUID> deletedItemFolderUUIDs = new HashSet<UUID>();
Array.ForEach<XInventoryItem>(retrievedItems, i => deletedItemFolderUUIDs.Add(i.parentFolderID));
foreach (UUID deletedItemFolderUUID in deletedItemFolderUUIDs)
IncrementFolderVersion(deletedItemFolderUUID);
return true;
}
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 (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.CommandText = String.Format("update {0} set parentFolderID = :ParentFolderID where inventoryID = :InventoryID", m_Realm);
cmd.Parameters.Add(new SQLiteParameter(":ParentFolderID", newParent));
cmd.Parameters.Add(new SQLiteParameter(":InventoryID", id));
if (ExecuteNonQuery(cmd, m_Connection) == 0)
return false;
}
IncrementFolderVersion(oldParent);
IncrementFolderVersion(newParent);
return true;
}
public XInventoryItem[] GetActiveGestures(UUID principalID)
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.CommandText = String.Format("select * from inventoryitems where avatarId = :uuid and assetType = :type and flags = 1", m_Realm);
cmd.Parameters.Add(new SQLiteParameter(":uuid", principalID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":type", (int)AssetType.Gesture));
return DoQuery(cmd);
}
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
IDataReader reader;
using (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.CommandText = String.Format("select inventoryCurrentPermissions from inventoryitems where avatarID = :PrincipalID and assetID = :AssetID", m_Realm);
cmd.Parameters.Add(new SQLiteParameter(":PrincipalID", principalID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":AssetID", assetID.ToString()));
reader = ExecuteReader(cmd, m_Connection);
}
int perms = 0;
while (reader.Read())
{
perms |= Convert.ToInt32(reader["inventoryCurrentPermissions"]);
}
reader.Close();
//CloseCommand(cmd);
return perms;
}
}
public class SqliteFolderHandler : SqliteInventoryHandler<XInventoryFolder>
{
public SqliteFolderHandler(string c, string t, string m) :
base(c, t, m)
{
}
public override bool Store(XInventoryFolder folder)
{
if (!base.Store(folder))
return false;
IncrementFolderVersion(folder.parentFolderID);
return true;
}
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 (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.CommandText = String.Format("update {0} set parentFolderID = :ParentFolderID where folderID = :FolderID", m_Realm);
cmd.Parameters.Add(new SQLiteParameter(":ParentFolderID", newParentFolderID));
cmd.Parameters.Add(new SQLiteParameter(":FolderID", id));
if (ExecuteNonQuery(cmd, m_Connection) == 0)
return false;
}
IncrementFolderVersion(oldParentFolderUUID);
IncrementFolderVersion(newParentFolderID);
return true;
}
}
public class SqliteInventoryHandler<T> : SQLiteGenericTableHandler<T> where T: class, new()
{
public SqliteInventoryHandler(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("[MYSQL ITEM HANDLER]: Incrementing version on folder {0}", folderID);
// Util.PrintCallStack();
using (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.CommandText = "update inventoryfolders set version=version+1 where folderID = :folderID";
cmd.Parameters.Add(new SQLiteParameter(":folderID", folderID));
if(ExecuteNonQuery(cmd, m_Connection) == 0)
return false;
}
return true;
}
}
}

View file

@ -25,9 +25,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModule.SharedBase;

View file

@ -25,9 +25,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModule.SharedBase;

View file

@ -24,15 +24,15 @@
* (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 OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenMetaverse;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using OpenSim.Region.PhysicsModule.SharedBase;
namespace OpenSim.Region.PhysicsModule.BulletS
{

View file

@ -25,9 +25,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModule.SharedBase;

View file

@ -25,9 +25,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModule.SharedBase;

View file

@ -40,6 +40,7 @@ using OpenMetaverse.StructuredData;
using PrimMesher;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using OpenSim.Region.PhysicsModules.ConvexDecompositionDotNet;
namespace OpenSim.Region.PhysicsModule.ubODEMeshing
{

View file

@ -149,10 +149,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Addons.Groups", "So
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Addons.OfflineIM", "Source\OpenSim.Addons.OfflineIM\OpenSim.Addons.OfflineIM.csproj", "{362A017B-80DE-4FA2-8AC3-0226F51AAB56}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Data.SQLite", "Source\OpenSim.Data.SQLite\OpenSim.Data.SQLite.csproj", "{AF2313C2-F8D3-4469-8C0F-D83842B62BE0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Data.PGSQL", "Source\OpenSim.Data.PGSQL\OpenSim.Data.PGSQL.csproj", "{12B7EA13-4A71-4BCF-9723-D6F07F6C89C4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenSim.Services.Controllers", "Source\OpenSim.Services.Controllers\OpenSim.Services.Controllers.csproj", "{CCABE946-99E9-4877-B6A7-6F53544D1739}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenSim.Server.AssetServer", "Source\OpenSim.Server.AssetServer\OpenSim.Server.AssetServer.csproj", "{7FC7566A-5B1E-4D36-BCC6-CEE993315C57}"
@ -411,14 +407,6 @@ Global
{362A017B-80DE-4FA2-8AC3-0226F51AAB56}.Debug|Any CPU.Build.0 = Debug|Any CPU
{362A017B-80DE-4FA2-8AC3-0226F51AAB56}.Release|Any CPU.ActiveCfg = Release|Any CPU
{362A017B-80DE-4FA2-8AC3-0226F51AAB56}.Release|Any CPU.Build.0 = Release|Any CPU
{AF2313C2-F8D3-4469-8C0F-D83842B62BE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AF2313C2-F8D3-4469-8C0F-D83842B62BE0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AF2313C2-F8D3-4469-8C0F-D83842B62BE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AF2313C2-F8D3-4469-8C0F-D83842B62BE0}.Release|Any CPU.Build.0 = Release|Any CPU
{12B7EA13-4A71-4BCF-9723-D6F07F6C89C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{12B7EA13-4A71-4BCF-9723-D6F07F6C89C4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{12B7EA13-4A71-4BCF-9723-D6F07F6C89C4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{12B7EA13-4A71-4BCF-9723-D6F07F6C89C4}.Release|Any CPU.Build.0 = Release|Any CPU
{CCABE946-99E9-4877-B6A7-6F53544D1739}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CCABE946-99E9-4877-B6A7-6F53544D1739}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CCABE946-99E9-4877-B6A7-6F53544D1739}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -494,8 +482,6 @@ Global
{B2038E44-5DED-4776-BDD5-1D7915C2A80B} = {8F448DF9-DE18-4810-8545-96DFE17D5C39}
{7AC7DE42-37C4-4AFE-BD39-CBF373E85A72} = {02C09046-CFF3-40BA-9E3F-629241EB25A5}
{362A017B-80DE-4FA2-8AC3-0226F51AAB56} = {02C09046-CFF3-40BA-9E3F-629241EB25A5}
{AF2313C2-F8D3-4469-8C0F-D83842B62BE0} = {02C09046-CFF3-40BA-9E3F-629241EB25A5}
{12B7EA13-4A71-4BCF-9723-D6F07F6C89C4} = {02C09046-CFF3-40BA-9E3F-629241EB25A5}
{CCABE946-99E9-4877-B6A7-6F53544D1739} = {02C09046-CFF3-40BA-9E3F-629241EB25A5}
{7FC7566A-5B1E-4D36-BCC6-CEE993315C57} = {02C09046-CFF3-40BA-9E3F-629241EB25A5}
EndGlobalSection

13
version.json Normal file
View file

@ -0,0 +1,13 @@
{
"$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/main/src/NerdBank.GitVersioning/version.schema.json",
"version": "0.9.3-beta",
"publicReleaseRefSpec": [
"^refs/heads/master$",
"^refs/heads/v\\d+(?:\\.\\d+)?$"
],
"cloudBuild": {
"buildNumber": {
"enabled": true
}
}
}