forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DatabaseStrategyNoDbSpecificFixture.cs
299 lines (249 loc) · 8.33 KB
/
DatabaseStrategyNoDbSpecificFixture.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using System;
using System.Data.Common;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Connection;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Engine;
using NHibernate.Linq;
using NHibernate.Mapping.ByCode;
using NHibernate.MultiTenancy;
using NHibernate.Util;
using NUnit.Framework;
namespace NHibernate.Test.MultiTenancy
{
[TestFixture]
public class DatabaseStrategyNoDbSpecificFixture : TestCaseMappingByCode
{
private Guid _id;
protected override void Configure(Configuration configuration)
{
configuration.Properties[Cfg.Environment.MultiTenant] = MultiTenancyStrategy.Database.ToString();
configuration.Properties[Cfg.Environment.GenerateStatistics] = true.ToString();
base.Configure(configuration);
}
[Test]
public void ShouldThrowWithNoTenantIdentifier()
{
var sessionBuilder = Sfi.WithOptions().TenantConfiguration(new TenantConfiguration(new MockConnectionProvider(null, null)));
Assert.That(() => sessionBuilder.OpenSession(), Throws.ArgumentException);
}
[Test]
public void ShouldThrowWithNoConnectionAccess()
{
var sessionBuilder = Sfi.WithOptions().TenantConfiguration(new TenantConfiguration(new MockConnectionProvider("tenant1", null)));
Assert.That(() => sessionBuilder.OpenSession(), Throws.ArgumentException);
}
[Test]
public void DifferentConnectionStringForDifferentTenants()
{
if (!IsSqlServerDialect)
Assert.Ignore("MSSqlServer specific test");
using(var session1 = OpenTenantSession("tenant1"))
using (var session2 = OpenTenantSession("tenant2"))
{
Assert.That(session1.Connection.ConnectionString, Is.Not.EqualTo(session2.Connection.ConnectionString));
ValidateSqlServerConnectionAppName(session1, "tenant1");
ValidateSqlServerConnectionAppName(session2, "tenant2");
}
}
private static void ValidateSqlServerConnectionAppName(ISession s, string tenantId)
{
var builder = new SqlConnectionStringBuilder(s.Connection.ConnectionString);
Assert.That(builder.ApplicationName, Is.EqualTo(tenantId));
}
[Test]
public void SecondLevelCacheReusedForSameTenant()
{
using (var sesTen1 = OpenTenantSession("tenant1"))
{
var entity = sesTen1.Get<Entity>(_id);
}
Sfi.Statistics.Clear();
using (var sesTen2 = OpenTenantSession("tenant1"))
{
var entity = sesTen2.Get<Entity>(_id);
}
Assert.That(Sfi.Statistics.PrepareStatementCount, Is.EqualTo(0));
Assert.That(Sfi.Statistics.SecondLevelCacheHitCount, Is.EqualTo(1));
}
[Test]
public void SecondLevelCacheSeparationPerTenant()
{
using (var sesTen1 = OpenTenantSession("tenant1"))
{
var entity = sesTen1.Get<Entity>(_id);
}
Sfi.Statistics.Clear();
using (var sesTen2 = OpenTenantSession("tenant2"))
{
var entity = sesTen2.Get<Entity>(_id);
}
Assert.That(Sfi.Statistics.PrepareStatementCount, Is.EqualTo(1));
Assert.That(Sfi.Statistics.SecondLevelCacheHitCount, Is.EqualTo(0));
}
[Test]
public void QueryCacheReusedForSameTenant()
{
using (var sesTen1 = OpenTenantSession("tenant1"))
{
var entity = sesTen1.Query<Entity>().WithOptions(x => x.SetCacheable(true)).Where(e => e.Id == _id).SingleOrDefault();
}
Sfi.Statistics.Clear();
using (var sesTen2 = OpenTenantSession("tenant1"))
{
var entity = sesTen2.Query<Entity>().WithOptions(x => x.SetCacheable(true)).Where(e => e.Id == _id).SingleOrDefault();
}
Assert.That(Sfi.Statistics.PrepareStatementCount, Is.EqualTo(0));
Assert.That(Sfi.Statistics.QueryCacheHitCount, Is.EqualTo(1));
}
[Test]
public void QueryCacheSeparationPerTenant()
{
using (var sesTen1 = OpenTenantSession("tenant1"))
{
var entity = sesTen1.Query<Entity>().WithOptions(x => x.SetCacheable(true)).Where(e => e.Id == _id).SingleOrDefault();
}
Sfi.Statistics.Clear();
using (var sesTen2 = OpenTenantSession("tenant2"))
{
var entity = sesTen2.Query<Entity>().WithOptions(x => x.SetCacheable(true)).Where(e => e.Id == _id).SingleOrDefault();
}
Assert.That(Sfi.Statistics.PrepareStatementCount, Is.EqualTo(1));
Assert.That(Sfi.Statistics.QueryCacheHitCount, Is.EqualTo(0));
}
[Test]
public void TenantSessionIsSerializableAndCanBeReconnected()
{
ISession deserializedSession = null;
using (var sesTen1 = OpenTenantSession("tenant1"))
{
var entity = sesTen1.Query<Entity>().WithOptions(x => x.SetCacheable(true)).Where(e => e.Id == _id).SingleOrDefault();
sesTen1.Disconnect();
deserializedSession = SpoofSerialization(sesTen1);
}
Sfi.Statistics.Clear();
using (deserializedSession)
{
deserializedSession.Reconnect();
var entity = deserializedSession.Get<Entity>(_id);
if (IsSqlServerDialect)
ValidateSqlServerConnectionAppName(deserializedSession, "tenant1");
}
Assert.That(Sfi.Statistics.PrepareStatementCount, Is.EqualTo(0));
Assert.That(Sfi.Statistics.QueryCacheHitCount, Is.EqualTo(0));
}
private ISession SpoofSerialization(ISession session)
{
var formatter = new BinaryFormatter
{
#if !NETFX
SurrogateSelector = new SerializationHelper.SurrogateSelector()
#endif
};
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, session);
stream.Position = 0;
return (ISession) formatter.Deserialize(stream);
}
private ISession OpenTenantSession(string tenantId)
{
return Sfi.WithOptions().TenantConfiguration(GetTenantConfig(tenantId)).OpenSession();
}
private TenantConfiguration GetTenantConfig(string tenantId)
{
return new TenantConfiguration(new TestTenantConnectionProvider(Sfi, tenantId, IsSqlServerDialect));
}
private bool IsSqlServerDialect => Sfi.Dialect is MsSql2000Dialect && !(Sfi.ConnectionProvider.Driver is OdbcDriver);
#region Test Setup
protected override HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.Class<Entity>(
rc =>
{
rc.Cache(m => m.Usage(CacheUsage.NonstrictReadWrite));
rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
rc.Property(x => x.Name);
});
return mapper.CompileMappingForAllExplicitlyAddedEntities();
}
protected override DbConnection OpenConnectionForSchemaExport()
{
return GetTenantConfig("defaultTenant").ConnectionAccess.GetConnection();
}
protected override ISession OpenSession()
{
return OpenTenantSession("defaultTenant");
}
protected override void OnTearDown()
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Delete("from System.Object");
session.Flush();
transaction.Commit();
}
}
protected override void OnSetUp()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
var e1 = new Entity {Name = "Bob"};
session.Save(e1);
var e2 = new Entity {Name = "Sally"};
session.Save(e2);
session.Flush();
transaction.Commit();
_id = e1.Id;
}
}
#endregion Test Setup
}
[Serializable]
class Entity
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
}
public class MockConnectionProvider : IMultiTenantConnectionProvider
{
private readonly IConnectionAccess _connectionAccess;
public MockConnectionProvider(string tenantIdentifier, IConnectionAccess connectionAccess)
{
_connectionAccess = connectionAccess;
TenantIdentifier = tenantIdentifier;
}
public string TenantIdentifier { get; }
public IConnectionAccess GetConnectionAccess()
{
return _connectionAccess;
}
}
[Serializable]
public class TestTenantConnectionProvider : AbstractMultiTenantConnectionProvider
{
public TestTenantConnectionProvider(ISessionFactoryImplementor sfi, string tenantId, bool isSqlServerDialect)
{
TenantIdentifier = tenantId;
SessionFactory = sfi;
TenantConnectionString = sfi.ConnectionProvider.GetConnectionString();
if (isSqlServerDialect)
{
var stringBuilder = new SqlConnectionStringBuilder(sfi.ConnectionProvider.GetConnectionString());
stringBuilder.ApplicationName = tenantId;
TenantConnectionString = stringBuilder.ToString();
}
}
protected override string TenantConnectionString { get; }
public override string TenantIdentifier { get; }
protected override ISessionFactoryImplementor SessionFactory { get; }
}
}