Datei: StressTests/StressTest/TestDatabase.cs

Last Commit (9de6a8c)
1 -- File didn't exist --
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
New Commit (bbf1d57)
1 using System;
2 using System.Collections.Generic;
3 using System.Data;
4 using System.Data.Common;
5 using System.IO;
6 using System.Linq;
7 using System.Text;
8 using System.Threading;
9 using System.Threading.Tasks;
10 using System.Xml.Linq;
11 using NDO;
12 using NDO.Mapping;
13 using NDO.ProviderFactory;
14 using NDOInterfaces;
15 using StressTestClasses;
16
17 namespace StressTest
18 {
19 ····/// <summary>
20 ····/// Provides PersistenceManager instances for the configured provider and creates the database schema.
21 ····/// </summary>
22 ····/// <remarks>
23 ····/// The mapping file of StressTestClasses contains a dummy connection. It is copied to a provider specific
24 ····/// mapping file, in which the connection type and connection string are replaced by the configured values.
25 ····/// The tables are generated with the ISqlGenerator of the provider from the DataSet, which NDO builds from the mapping.
26 ····/// </remarks>
27 ····public class TestDatabase
28 ····{
29 ········readonly StressTestOptions options;
30 ········readonly NDOMapping sharedMapping;
31
32 ········public string MappingFile { get; }
33
34 ········public TestDatabase( StressTestOptions options )
35 ········{
36 ············this.options = options;
37
38 ············var mappingSource = Path.Combine( AppContext.BaseDirectory, "StressTestClasses.NDOMapping.xml" );
39 ············XDocument doc = XDocument.Load( mappingSource );
40 ············foreach (var conn in doc.Descendants( "Connection" ))
41 ············{
42 ················conn.SetAttributeValue( "Type", options.Provider );
43 ················conn.SetAttributeValue( "Name", options.ConnectionString );
44 ············}
45 ············MappingFile = Path.Combine( AppContext.BaseDirectory, $"NDOMapping.{options.Provider}.xml" );
46 ············doc.Save( MappingFile );
47
48 ············if (options.SharedMapping)
49 ············{
50 ················// The mapping object stays valid after the PersistenceManager is closed.
51 ················using (var pm = new PersistenceManager( MappingFile ))
52 ····················this.sharedMapping = pm.NDOMapping;
53 ············}
54 ········}
55
56 ········/// <summary>
57 ········/// Creates a new PersistenceManager. Each worker must use its own instances.
58 ········/// </summary>
59 ········public PersistenceManager NewPersistenceManager()
60 ········{
61 ············var pm = this.sharedMapping != null
62 ················? new PersistenceManager( this.sharedMapping )
63 ················: new PersistenceManager( MappingFile );
64 ············pm.TransactionMode = this.options.TransactionMode;
65 ············if (this.options.IsolationLevel.HasValue)
66 ················pm.IsolationLevel = this.options.IsolationLevel.Value;
67 ············return pm;
68 ········}
69
70 ········IProvider GetProvider( PersistenceManager pm, out ISqlGenerator generator )
71 ········{
72 ············Connection conn = pm.NDOMapping.Connections.First();
73 ············IProvider provider = pm.NDOMapping.GetProvider( conn );
74 ············if (provider == null)
75 ················throw new Exception( $"Provider '{this.options.Provider}' not found. Available providers: {String.Join( ", ", NDOProviderFactory.Instance.ProviderNames )}" );
76 ············if (!NDOProviderFactory.Instance.Generators.TryGetValue( this.options.Provider, out generator ))
77 ················throw new Exception( $"No ISqlGenerator for provider '{this.options.Provider}' found." );
78 ············generator.Provider = provider;
79 ············return provider;
80 ········}
81
82 ········/// <summary>
83 ········/// Quotes a table name, which might contain a schema name.
84 ········/// </summary>
85 ········static string QualifiedTableName( IProvider provider, string name )
86 ········{
87 ············return String.Join( ".", name.Split( '.' ).Select( n => provider.GetQuotedName( n ) ) );
88 ········}
89
90 ········static string UnqualifiedName( string name )
91 ········{
92 ············int p = name.LastIndexOf( '.' );
93 ············if (p > -1)
94 ················name = name.Substring( p + 1 );
95 ············return name.Trim( '"', '`', '[', ']' );
96 ········}
97
98 ········async Task<HashSet<string>> GetExistingTablesAsync( IProvider provider, CancellationToken ct )
99 ········{
100 ············using (DbConnection conn = provider.NewConnection( this.options.ConnectionString ))
101 ············{
102 ················await conn.OpenAsync( ct );
103 ················return new HashSet<string>( provider.GetTableNames( conn ).Select( UnqualifiedName ), StringComparer.OrdinalIgnoreCase );
104 ············}
105 ········}
106
107 ········/// <summary>
108 ········/// Executes each statement in its own transaction.
109 ········/// </summary>
110 ········async Task ExecuteAsync( string sql, CancellationToken ct )
111 ········{
112 ············// Some databases (e.g. Oracle) don't accept the statement terminator in a command
113 ············sql = sql.Trim().TrimEnd( ';' );
114 ············await using (var pm = NewPersistenceManager())
115 ············await using (var handler = pm.GetSqlPassThroughHandler())
116 ············{
117 ················await handler.ExecuteAsync( sql, false, null, ct );
118 ················await handler.CommitTransactionAsync( ct );
119 ············}
120 ········}
121
122 ········public async Task DropSchemaAsync( CancellationToken ct = default )
123 ········{
124 ············await using (var pm = NewPersistenceManager())
125 ············{
126 ················IProvider provider = GetProvider( pm, out ISqlGenerator generator );
127 ················var existing = await GetExistingTablesAsync( provider, ct );
128 ················foreach (DataTable dt in pm.DataSet.Tables)
129 ················{
130 ····················if (existing.Contains( UnqualifiedName( dt.TableName ) ))
131 ························await ExecuteAsync( generator.DropTable( QualifiedTableName( provider, dt.TableName ) ), ct );
132 ················}
133 ············}
134 ········}
135
136 ········public async Task CreateSchemaAsync( CancellationToken ct = default )
137 ········{
138 ············await using (var pm = NewPersistenceManager())
139 ············{
140 ················IProvider provider = GetProvider( pm, out ISqlGenerator generator );
141 ················foreach (DataTable dt in pm.DataSet.Tables)
142 ················{
143 ····················foreach (string statement in CreateTableStatements( dt, pm.NDOMapping, provider, generator ))
144 ························await ExecuteAsync( statement, ct );
145 ················}
146 ············}
147 ········}
148
149 ········/// <summary>
150 ········/// Generates the CREATE TABLE statement in the same way as the GenericSqlGenerator of the NDOEnhancer.
151 ········/// </summary>
152 ········static IEnumerable<string> CreateTableStatements( DataTable dt, NDOMapping mapping, IProvider provider, ISqlGenerator generator )
153 ········{
154 ············string tableName = QualifiedTableName( provider, dt.TableName );
155 ············Class cl = mapping.Classes.FirstOrDefault( c => c.TableName == dt.TableName );
156 ············DataColumn[] pk = dt.PrimaryKey;
157 ············var placement = generator.PrimaryConstraintPlacement;
158 ············// A combined primary key can't be declared in the column definitions
159 ············if (pk.Length > 1 && placement == PrimaryConstraintPlacement.InColumn)
160 ················placement = PrimaryConstraintPlacement.InTable;
161
162 ············var columns = new List<string>();
163 ············foreach (DataColumn dc in dt.Columns)
164 ················columns.Add( CreateColumn( dc, cl, provider, generator, pk.Length == 1 && pk.Contains( dc ) && placement == PrimaryConstraintPlacement.InColumn, pk.Contains( dc ) ) );
165
166 ············string pkConstraint = null;
167 ············if (pk.Length > 0 && placement != PrimaryConstraintPlacement.InColumn)
168 ················pkConstraint = generator.CreatePrimaryKeyConstraint( pk, provider.GetQuotedName( "PK_" + UnqualifiedName( dt.TableName ) ), tableName );
169
170 ············var sb = new StringBuilder();
171 ············sb.Append( generator.BeginnTable( tableName ) ).Append( '\n' );
172 ············sb.Append( String.Join( ",\n", columns ) );
173 ············if (pkConstraint != null && placement == PrimaryConstraintPlacement.InTable)
174 ················sb.Append( ",\n" ).Append( pkConstraint );
175 ············sb.Append( '\n' ).Append( generator.EndTable( tableName ) );
176 ············yield return sb.ToString();
177
178 ············if (pkConstraint != null && placement == PrimaryConstraintPlacement.AfterTable)
179 ················yield return pkConstraint;
180 ········}
181
182 ········static string CreateColumn( DataColumn dc, Class cl, IProvider provider, ISqlGenerator generator, bool primaryKeyInColumn, bool isPrimary )
183 ········{
184 ············string name = provider.GetQuotedName( dc.ColumnName );
185 ············string columnType = null;
186 ············string width = null;
187 ············string precision = null;
188 ············bool allowNull = true;
189 ············int size = 0;
190
191 ············Field field = cl?.Fields.FirstOrDefault( f => f.Column.Name == dc.ColumnName );
192 ············if (field != null)
193 ············{
194 ················columnType = field.Column.DbType;
195 ················size = field.Column.Size;
196 ················if (size != 0)
197 ····················width = size.ToString();
198 ················if (field.Column.Precision != 0)
199 ····················precision = field.Column.Precision.ToString();
200 ················allowNull = field.Column.AllowDbNull;
201 ············}
202
203 ············bool autoIncrement = field == null && isPrimary && dc.AutoIncrement;
204
205 ············if (columnType == null)
206 ················columnType = generator.DbTypeFromType( dc.DataType, size );
207
208 ············if (width == null)
209 ············{
210 ················int dl = provider.GetDefaultLength( dc.DataType );
211 ················if (dl != 0)
212 ····················width = dl.ToString();
213 ············}
214
215 ············if (precision == null && dc.DataType == typeof( decimal ))
216 ················precision = "2";
217
218 ············if (!generator.LengthAllowed( columnType ))
219 ················width = null;
220
221 ············string definition;
222 ············if (autoIncrement && generator.HasSpecialAutoIncrementColumnFormat)
223 ················definition = generator.AutoIncrementColumn( name, dc.DataType, columnType, width, isPrimary );
224 ············else if (primaryKeyInColumn)
225 ················definition = generator.PrimaryKeyColumn( name, dc.DataType, columnType, width );
226 ············else if (width != null && precision != null)
227 ················definition = $"{name} {columnType}({width},{precision})";
228 ············else if (width != null)
229 ················definition = $"{name} {columnType}({width})";
230 ············else
231 ················definition = $"{name} {columnType}";
232
233 ············return definition + " " + generator.NullExpression( allowNull && dc.AllowDBNull );
234 ········}
235
236 ········/// <summary>
237 ········/// Creates the tags, which are shared by all workers.
238 ········/// </summary>
239 ········/// <returns>The ids of the tags</returns>
240 ········public async Task<int[]> CreateTagsAsync( int count, CancellationToken ct = default )
241 ········{
242 ············await using (var pm = NewPersistenceManager())
243 ············{
244 ················var tags = new List<Tag>();
245 ················for (int i = 0; i < count; i++)
246 ················{
247 ····················var tag = new Tag() { Name = $"Tag{i}" };
248 ····················pm.MakePersistent( tag );
249 ····················tags.Add( tag );
250 ················}
251 ················await pm.SaveAsync( false, ct );
252 ················return tags.Select( t => (int) ((IPersistenceCapable) t).NDOObjectId.Id[0] ).ToArray();
253 ············}
254 ········}
255
256 ········public class RowCounts
257 ········{
258 ············public int Customers;
259 ············public int Orders;
260 ············public int OrderLines;
261 ············public int Tags;
262 ············public long MappingTableEntries;
263
264 ············public override string ToString() => $"Customers: {Customers}, Orders: {Orders}, OrderLines: {OrderLines}, Tags: {Tags}, Order-Tag relations: {MappingTableEntries}";
265 ········}
266
267 ········public async Task<RowCounts> GetRowCountsAsync( CancellationToken ct = default )
268 ········{
269 ············var result = new RowCounts();
270 ············await using (var pm = NewPersistenceManager())
271 ············{
272 ················result.Customers = await pm.Objects<Customer>().CountAsync( ct );
273 ················result.Orders = await pm.Objects<SalesOrder>().CountAsync( ct );
274 ················result.OrderLines = await pm.Objects<OrderLine>().CountAsync( ct );
275 ················result.Tags = await pm.Objects<Tag>().CountAsync( ct );
276 ············}
277
278 ············// The mapping table has no class, so we count it with SQL.
279 ············// We use a separate PersistenceManager: GetSqlPassThroughHandler() uses a new Connection object,
280 ············// so in pessimistic mode the handler would open a second transaction besides the one of the queries above,
281 ············// which blocks e.g. with Sqlite and IsolationLevel.Serializable.
282 ············await using (var pm = NewPersistenceManager())
283 ············{
284 ················var relation = pm.NDOMapping.FindClass( typeof( SalesOrder ) ).Relations.Single( r => r.FieldName == "tags" );
285 ················IProvider provider = GetProvider( pm, out _ );
286 ················string table = QualifiedTableName( provider, relation.MappingTable.TableName );
287 ················await using (var handler = pm.GetSqlPassThroughHandler())
288 ················{
289 ····················await using (DbDataReader reader = await handler.ExecuteAsync( $"SELECT COUNT(*) FROM {table}", true, null, ct ))
290 ····················{
291 ························await reader.ReadAsync( ct );
292 ························result.MappingTableEntries = Convert.ToInt64( reader.GetValue( 0 ) );
293 ····················}
294 ····················await handler.CommitTransactionAsync( ct );
295 ················}
296 ············}
297 ············return result;
298 ········}
299 ····}
300 }
301