Datei: StressTests/StressTest/Worker.cs

Last Commit (bbf1d57)
1 using System;
2 using System.Collections.Generic;
 
3 using System.Linq;
4 using System.Threading;
5 using System.Threading.Tasks;
6 using NDO;
7 using NDO.Linq;
8 using StressTestClasses;
9
10 namespace StressTest
11 {
12 ····/// <summary>
13 ····/// Thrown if the data read from the database doesn't match the expected data.
14 ····/// </summary>
15 ····public class VerificationException : Exception
16 ····{
17 ········public VerificationException( string message ) : base( message )
18 ········{
19 ········}
20 ····}
21
22 ····/// <summary>
23 ····/// A worker runs the test scenario in a loop. All database operations use the async API of NDO.
24 ····/// </summary>
25 ····/// <remarks>
26 ····/// Each step uses a new PersistenceManager, so that the data is really read from the database
27 ····/// and not from the cache of a PersistenceManager. The data of a worker is identified by the run id,
28 ····/// the worker number and the iteration, so that the workers don't interfere with each other, except
29 ····/// for the tags, which are shared by all workers.
30 ····/// </remarks>
31 ····public class Worker
32 ····{
33 ········readonly int workerNo;
34 ········readonly TestDatabase db;
35 ········readonly StressTestOptions options;
36 ········readonly Statistics statistics;
37 ········readonly int[] tagIds;
38 ········readonly string runId;
39 ········readonly Random random;
40
41 ········public Worker( int workerNo, TestDatabase db, StressTestOptions options, Statistics statistics, int[] tagIds, string runId )
42 ········{
43 ············this.workerNo = workerNo;
44 ············this.db = db;
45 ············this.options = options;
46 ············this.statistics = statistics;
47 ············this.tagIds = tagIds;
48 ············this.runId = runId;
49 ············this.random = new Random( workerNo );
50 ········}
51
52 ········static void Check( bool condition, string message )
53 ········{
54 ············if (!condition)
55 ················throw new VerificationException( message );
56 ········}
57
58 ········static int IdOf( object o ) => (int) ((IPersistenceCapable) o).NDOObjectId.Id[0];
59
60 ········/// <summary>
61 ········/// Runs the iterations until the number of iterations is reached, the time is up or cancellation is requested.
62 ········/// </summary>
63 ········/// <param name="endTime">If not null, the worker runs until this time instead of a fixed number of iterations.</param>
64 ········/// <param name="ct"></param>
65 ········public async Task RunAsync( DateTime? endTime, CancellationToken ct )
66 ········{
67 ············for (int iteration = 0; ; iteration++)
68 ············{
69 ················if (ct.IsCancellationRequested)
70 ····················break;
71 ················if (endTime.HasValue ? DateTime.UtcNow >= endTime.Value : iteration >= this.options.Iterations)
72 ····················break;
73
74 ················var state = new IterationState( $"{this.runId}-{this.workerNo}-{iteration}" );
75 ················try
76 ················{
77 ····················await RunIterationAsync( state, ct );
78 ····················this.statistics.IterationSucceeded();
79 ················}
80 ················catch (OperationCanceledException) when (ct.IsCancellationRequested)
81 ················{
82 ····················break;
83 ················}
84 ················catch (Exception ex)
85 ················{
86 ····················this.statistics.IterationFailed( new Statistics.ErrorInfo { Worker = this.workerNo, Iteration = iteration, Step = state.Step, Exception = ex } );
87 ····················if (this.options.StopOnFirstError)
88 ························throw;
89 ················}
90 ············}
91 ········}
92
93 ········class IterationState
94 ········{
95 ············public IterationState( string key )
96 ············{
97 ················OrderNumber = "O-" + key;
98 ················CustomerName = "C-" + key;
99 ············}
100
101 ············public string Step;
102 ············public readonly string OrderNumber;
103 ············public readonly string CustomerName;
104 ············public int OrderId;
105 ············public HashSet<int> ExpectedTagIds;
106 ············public int ExpectedLineCount;
107 ············public decimal ExpectedPriceSum;
108 ············public decimal ExpectedTotal;
109 ········}
110
111 ········async Task RunIterationAsync( IterationState s, CancellationToken ct )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112 ········{
113 s. Step = "Create";
114 await CreateAsync( s, ct ) ;
115 s. Step = "Read and change";
116 await ChangeAsync( s, ct ) ;
117 s. Step = "Verify";
118 await VerifyAsync( s, ct ) ;
119 ············s.Step = "Query";
120 ············await QueryAsync( ct );
121 ············s.Step = "Delete";
122 ············await DeleteAsync( s, ct );
123 ············s.Step = "Verify deletion";
124 ············await VerifyDeletionAsync( s, ct );
125 ········}
126
127 ········/// <summary>
128 ········/// Creates a customer and an order with lines and two tags.
129 ········/// </summary>
130 ········async Task CreateAsync( IterationState s, CancellationToken ct )
131 ········{
132 ············await using (var pm = this.db.NewPersistenceManager())
133 ············{
134 ················var customer = new Customer()
135 ················{
136 ····················Name = s.CustomerName,
137 ····················City = "City" + this.workerNo,
138 ····················// Some databases don't store fractions of seconds
139 ····················Created = new DateTime( 2026, 1, 1, 12, 0, 0 ).AddMinutes( this.workerNo )
140 ················};
141
142 ················var order = new SalesOrder()
143 ················{
144 ····················OrderNumber = s.OrderNumber,
145 ····················OrderDate = DateTime.Today,
146 ····················Status = "New",
147 ····················Customer = customer
148 ················};
149
150 ················for (int i = 0; i < this.options.LinesPerOrder; i++)
151 ····················order.NewLine( "Product" + i, i + 1, 1.25m * (i + 1) );
152 ················order.Total = order.ComputeTotal();
153
154 ················// FindObject creates hollow objects without database access
155 ················var tagIndexes = PickDistinct( 2 );
156 ················foreach (int index in tagIndexes)
157 ····················order.AddTag( (Tag) pm.FindObject( typeof( Tag ), this.tagIds[index] ) );
158
159 ················pm.MakePersistent( customer );
160 ················pm.MakePersistent( order );
161 ················await this.statistics.MeasureAsync( "SaveAsync (insert)", () => pm.SaveAsync( false, ct ) );
162
163 ················s.OrderId = IdOf( order );
164 ················Check( s.OrderId > 0, $"Order {s.OrderNumber} didn't get an id." );
165 ················Check( order.Lines.All( l => IdOf( l ) > 0 ), $"Not all lines of order {s.OrderNumber} got an id." );
166 ················s.ExpectedTagIds = new HashSet<int>( tagIndexes.Select( i => this.tagIds[i] ) );
167 ············}
168 ········}
169
170 ········/// <summary>
171 ········/// Reads the order, changes fields, lines, tags and the customer and saves the changes.
172 ········/// </summary>
173 ········async Task ChangeAsync( IterationState s, CancellationToken ct )
174 ········{
175 ············await using (var pm = this.db.NewPersistenceManager())
176 ············{
177 ················var order = await this.statistics.MeasureAsync( "VirtualTable.SingleAsync",
178 ····················() => pm.Objects<SalesOrder>().Where( o => o.OrderNumber == s.OrderNumber ).SingleAsync( ct ) );
179 ················Check( IdOf( order ) == s.OrderId, $"Order {s.OrderNumber}: wrong id {IdOf( order )}, expected {s.OrderId}." );
180
181 ················await this.statistics.MeasureAsync( "LoadRelationAsync", () => pm.LoadRelationAsync( order, "lines", false, ct ) );
182 ················await this.statistics.MeasureAsync( "LoadRelationAsync", () => pm.LoadRelationAsync( order, "tags", false, ct ) );
183 ················var lines = order.Lines.ToList();
184 ················Check( lines.Count == this.options.LinesPerOrder, $"Order {s.OrderNumber}: {lines.Count} lines read, expected {this.options.LinesPerOrder}." );
185 ················var tagIdsRead = new HashSet<int>( order.Tags.Select( IdOf ) );
186 ················Check( tagIdsRead.SetEquals( s.ExpectedTagIds ), $"Order {s.OrderNumber}: wrong tags [{String.Join( ",", tagIdsRead )}], expected [{String.Join( ",", s.ExpectedTagIds )}]." );
187
188 ················Customer customer = order.Customer;
189 ················Check( customer != null, $"Order {s.OrderNumber} has no customer." );
190 ················await this.statistics.MeasureAsync( "LoadDataAsync", () => pm.LoadDataAsync( customer, ct ) );
191 ················Check( customer.Name == s.CustomerName, $"Order {s.OrderNumber}: wrong customer '{customer.Name}', expected '{s.CustomerName}'." );
192
193 ················// Change fields, change a line, remove a line, add a line
194 ················order.Status = "Changed";
195 ················var first = lines.OrderBy( l => l.Product ).First();
196 ················first.Quantity += 10;
197 ················order.RemoveLine( lines.OrderBy( l => l.Product ).Last() );
198 ················order.NewLine( "Extra", 7, 3.5m );
199 ················order.Total = order.ComputeTotal();
200
201 ················// Replace one tag by another one
202 ················var removedTag = order.Tags.First();
203 ················order.RemoveTag( removedTag );
204 ················int newTagId = this.tagIds.First( id => !s.ExpectedTagIds.Contains( id ) );
205 ················order.AddTag( (Tag) pm.FindObject( typeof( Tag ), newTagId ) );
206
207 ················customer.UpdateCount++;
208
209 ················await this.statistics.MeasureAsync( "SaveAsync (update)", () => pm.SaveAsync( false, ct ) );
210
211 ················s.ExpectedTagIds.Remove( IdOf( removedTag ) );
212 ················s.ExpectedTagIds.Add( newTagId );
213 ················s.ExpectedLineCount = order.Lines.Count();
214 ················s.ExpectedPriceSum = order.Lines.Sum( l => l.Price );
215 ················s.ExpectedTotal = order.Total;
216 ············}
217 ········}
218
219 ········/// <summary>
220 ········/// Checks the changes with a new PersistenceManager.
221 ········/// </summary>
222 ········async Task VerifyAsync( IterationState s, CancellationToken ct )
223 ········{
224 ············await using (var pm = this.db.NewPersistenceManager())
225 ············{
226 ················int orderId = s.OrderId;
227 ················var lineQuery = pm.Objects<OrderLine>().Where( l => l.Order.Oid() == orderId );
228
229 ················var lines = await this.statistics.MeasureAsync( "VirtualTable.ToListAsync", () => lineQuery.ToListAsync( ct ) );
230 ················Check( lines.Count == s.ExpectedLineCount, $"Order {s.OrderNumber}: {lines.Count} lines found, expected {s.ExpectedLineCount}." );
231 ················Check( lines.Any( l => l.Product == "Extra" ), $"Order {s.OrderNumber}: the added line is missing." );
232 ················Check( !lines.Any( l => l.Product == "Product" + (this.options.LinesPerOrder - 1) ), $"Order {s.OrderNumber}: the removed line still exists." );
233
234 ················int count = await this.statistics.MeasureAsync( "VirtualTable.CountAsync", () => lineQuery.CountAsync( ct ) );
235 ················Check( count == s.ExpectedLineCount, $"Order {s.OrderNumber}: CountAsync returns {count}, expected {s.ExpectedLineCount}." );
236
237 ················// Note: Sum over an int field doesn't work, because NDO always computes sums as decimal and casts the result to TP
238 ················decimal priceSum = await this.statistics.MeasureAsync( "VirtualTable.SumAsync", () => lineQuery.SumAsync( l => l.Price, ct ) );
239 ················Check( priceSum == s.ExpectedPriceSum, $"Order {s.OrderNumber}: SumAsync returns {priceSum}, expected {s.ExpectedPriceSum}." );
240
241 ················// await foreach over a VirtualTable with a condition on a related object
242 ················string customerName = s.CustomerName;
243 ················var orders = await this.statistics.MeasureAsync( "VirtualTable await foreach", async () =>
244 ················{
245 ····················var result = new List<SalesOrder>();
246 ····················await foreach (var o in pm.Objects<SalesOrder>().Where( o => o.Customer.Name == customerName ).AsAsyncEnumerable( ct ))
247 ························result.Add( o );
248 ····················return result;
249 ················} );
250 ················Check( orders.Count == 1, $"Customer {customerName}: {orders.Count} orders found, expected 1." );
251
252 ················var order = orders[0];
253 ················Check( order.OrderNumber == s.OrderNumber, $"Customer {customerName}: wrong order {order.OrderNumber}, expected {s.OrderNumber}." );
254 ················Check( order.Status == "Changed", $"Order {s.OrderNumber}: status '{order.Status}', expected 'Changed'." );
255 ················Check( order.Total == s.ExpectedTotal, $"Order {s.OrderNumber}: total {order.Total}, expected {s.ExpectedTotal}." );
256 ················decimal linesTotal = lines.Sum( l => l.Quantity * l.Price );
257 ················Check( linesTotal == s.ExpectedTotal, $"Order {s.OrderNumber}: the lines sum up to {linesTotal}, expected {s.ExpectedTotal}." );
258
259 ················await this.statistics.MeasureAsync( "LoadRelationAsync", () => pm.LoadRelationAsync( order, "tags", false, ct ) );
260 ················var tagIdsRead = new HashSet<int>( order.Tags.Select( IdOf ) );
261 ················Check( tagIdsRead.SetEquals( s.ExpectedTagIds ), $"Order {s.OrderNumber}: wrong tags [{String.Join( ",", tagIdsRead )}], expected [{String.Join( ",", s.ExpectedTagIds )}]." );
262
263 ················var customer = await this.statistics.MeasureAsync( "VirtualTable.FirstOrDefaultAsync",
264 ····················() => pm.Objects<Customer>().Where( c => c.Name == customerName ).FirstOrDefaultAsync( ct ) );
265 ················Check( customer != null, $"Customer {customerName} not found." );
266 ················Check( customer.UpdateCount == 1, $"Customer {customerName}: UpdateCount is {customer.UpdateCount}, expected 1." );
267
268 ················// RefreshAsync reads the object again
269 ················await this.statistics.MeasureAsync( "RefreshAsync", () => pm.RefreshAsync( customer, ct ) );
270 ················Check( customer.UpdateCount == 1, $"Customer {customerName}: UpdateCount after RefreshAsync is {customer.UpdateCount}, expected 1." );
271 ············}
272 ········}
273
274 ········/// <summary>
275 ········/// Queries, which read data of other workers. The results can't be checked, because the other workers change the data.
276 ········/// </summary>
277 ········async Task QueryAsync( CancellationToken ct )
278 ········{
279 ············await using (var pm = this.db.NewPersistenceManager())
280 ············{
281 ················await this.statistics.MeasureAsync( "VirtualTable.CountAsync", () => pm.Objects<SalesOrder>().Where( o => o.Status == "Changed" ).CountAsync( ct ) );
282 ················var page = await this.statistics.MeasureAsync( "VirtualTable paged",
283 ····················() => pm.Objects<SalesOrder>().OrderByDescending( o => o.OrderNumber ).Take( 10 ).ToListAsync( ct ) );
284 ················Check( page.Count <= 10, $"Take(10) returned {page.Count} objects." );
285 ················int tagCount = await this.statistics.MeasureAsync( "VirtualTable.CountAsync", () => pm.Objects<Tag>().CountAsync( ct ) );
286 ················Check( tagCount == this.tagIds.Length, $"{tagCount} tags found, expected {this.tagIds.Length}." );
287 ············}
288 ········}
289
290 ········/// <summary>
291 /// Deletes the order with PersistenceManager. Delete ( the composite relation deletes the lines and the mapping table entries)
292 ········/// and the customer with VirtualTable.DeleteDirectlyAsync.
293 ········/// </summary>
294 async Task DeleteAsync( IterationState s, CancellationToken ct )
295 ········{
296 ············await using (var pm = this.db.NewPersistenceManager())
297 ············{
298 ················var order = await this.statistics.MeasureAsync( "VirtualTable.SingleAsync",
299 ····················() => pm.Objects<SalesOrder>().Where( o => o.OrderNumber == s.OrderNumber ).SingleAsync( ct ) );
300 ················pm.Delete( order );
301 ················await this.statistics.MeasureAsync( "SaveAsync (delete)", () => pm.SaveAsync( false, ct ) );
 
302 ············}
303
 
 
 
 
 
304 ············await using (var pm = this.db.NewPersistenceManager())
305 ············{
306 ················string customerName = s.CustomerName;
307 ················await this.statistics.MeasureAsync( "VirtualTable.DeleteDirectlyAsync",
308 ····················() => pm.Objects<Customer>().Where( c => c.Name == customerName ).DeleteDirectlyAsync( ct ) );
309 ············}
310 ········}
311
312 ········async Task VerifyDeletionAsync( IterationState s, CancellationToken ct )
313 ········{
314 ············await using (var pm = this.db.NewPersistenceManager())
315 ············{
316 ················string orderNumber = s.OrderNumber;
317 ················string customerName = s.CustomerName;
318 ················int orderId = s.OrderId;
319
320 ················int orders = await pm.Objects<SalesOrder>().Where( o => o.OrderNumber == orderNumber ).CountAsync( ct );
321 ················Check( orders == 0, $"Order {orderNumber} still exists after deletion." );
322 ················int lines = await pm.Objects<OrderLine>().Where( l => l.Order.Oid() == orderId ).CountAsync( ct );
323 ················Check( lines == 0, $"Order {orderNumber}: {lines} lines still exist after deletion." );
324 ················int customers = await pm.Objects<Customer>().Where( c => c.Name == customerName ).CountAsync( ct );
325 ················Check( customers == 0, $"Customer {customerName} still exists after DeleteDirectlyAsync." );
326 ············}
327 ········}
328
329 ········int[] PickDistinct( int count )
330 ········{
331 ············return Enumerable.Range( 0, this.tagIds.Length ).OrderBy( _ => this.random.Next() ).Take( count ).ToArray();
332 ········}
333 ····}
334 }
335
New Commit (4a40b5b)
1 using System;
2 using System.Collections.Generic;
3 using System.Data.Common;
4 using System.Linq;
5 using System.Threading;
6 using System.Threading.Tasks;
7 using NDO;
8 using NDO.Linq;
9 using StressTestClasses;
10
11 namespace StressTest
12 {
13 ····/// <summary>
14 ····/// Thrown if the data read from the database doesn't match the expected data.
15 ····/// </summary>
16 ····public class VerificationException : Exception
17 ····{
18 ········public VerificationException( string message ) : base( message )
19 ········{
20 ········}
21 ····}
22
23 ····/// <summary>
24 ····/// A worker runs the test scenario in a loop. All database operations use the async API of NDO.
25 ····/// </summary>
26 ····/// <remarks>
27 ····/// Each step uses a new PersistenceManager, so that the data is really read from the database
28 ····/// and not from the cache of a PersistenceManager. The data of a worker is identified by the run id,
29 ····/// the worker number and the iteration, so that the workers don't interfere with each other, except
30 ····/// for the tags, which are shared by all workers.
31 ····/// </remarks>
32 ····public class Worker
33 ····{
34 ········readonly int workerNo;
35 ········readonly TestDatabase db;
36 ········readonly StressTestOptions options;
37 ········readonly Statistics statistics;
38 ········readonly int[] tagIds;
39 ········readonly string runId;
40 ········readonly Random random;
41
42 ········public Worker( int workerNo, TestDatabase db, StressTestOptions options, Statistics statistics, int[] tagIds, string runId )
43 ········{
44 ············this.workerNo = workerNo;
45 ············this.db = db;
46 ············this.options = options;
47 ············this.statistics = statistics;
48 ············this.tagIds = tagIds;
49 ············this.runId = runId;
50 ············this.random = new Random( workerNo );
51 ········}
52
53 ········static void Check( bool condition, string message )
54 ········{
55 ············if (!condition)
56 ················throw new VerificationException( message );
57 ········}
58
59 ········static int IdOf( object o ) => (int) ((IPersistenceCapable) o).NDOObjectId.Id[0];
60
61 ········/// <summary>
62 ········/// Runs the iterations until the number of iterations is reached, the time is up or cancellation is requested.
63 ········/// </summary>
64 ········/// <param name="endTime">If not null, the worker runs until this time instead of a fixed number of iterations.</param>
65 ········/// <param name="ct"></param>
66 ········public async Task RunAsync( DateTime? endTime, CancellationToken ct )
67 ········{
68 ············for (int iteration = 0; ; iteration++)
69 ············{
70 ················if (ct.IsCancellationRequested)
71 ····················break;
72 ················if (endTime.HasValue ? DateTime.UtcNow >= endTime.Value : iteration >= this.options.Iterations)
73 ····················break;
74
75 ················var state = new IterationState( $"{this.runId}-{this.workerNo}-{iteration}" );
76 ················try
77 ················{
78 ····················await RunIterationAsync( state, ct );
79 ····················this.statistics.IterationSucceeded();
80 ················}
81 ················catch (OperationCanceledException) when (ct.IsCancellationRequested)
82 ················{
83 ····················break;
84 ················}
85 ················catch (Exception ex)
86 ················{
87 ····················this.statistics.IterationFailed( new Statistics.ErrorInfo { Worker = this.workerNo, Iteration = iteration, Step = state.Step, Exception = ex } );
88 ····················if (this.options.StopOnFirstError)
89 ························throw;
90 ················}
91 ············}
92 ········}
93
94 ········class IterationState
95 ········{
96 ············public IterationState( string key )
97 ············{
98 ················OrderNumber = "O-" + key;
99 ················CustomerName = "C-" + key;
100 ············}
101
102 ············public string Step;
103 ············public readonly string OrderNumber;
104 ············public readonly string CustomerName;
105 ············public int OrderId;
106 ············public HashSet<int> ExpectedTagIds;
107 ············public int ExpectedLineCount;
108 ············public decimal ExpectedPriceSum;
109 ············public decimal ExpectedTotal;
110 ········}
111
112 ········async Task RunIterationAsync( IterationState s, CancellationToken ct )
113 ········{
114 ············await RunStepAsync( s, "Create", () => CreateAsync( s, ct ), ct );
115 ············await RunStepAsync( s, "Read and change", () => ChangeAsync( s, ct ), ct );
116 ············await RunStepAsync( s, "Verify", () => VerifyAsync( s, ct ), ct );
117 ············await RunStepAsync( s, "Query", () => QueryAsync( ct ), ct );
118 ············await RunStepAsync( s, "Delete", () => DeleteOrderAsync( s, ct ), ct );
119 ············await RunStepAsync( s, "Delete", () => DeleteCustomerAsync( s, ct ), ct );
120 ············await RunStepAsync( s, "Verify deletion", () => VerifyDeletionAsync( s, ct ), ct );
121 ········}
122
123 ········/// <summary>
124 ········/// Runs a step and repeats it, if the database chose its transaction as deadlock victim.
125 ········/// </summary>
126 ········/// <remarks>
127 ········/// Deadlocks can't be avoided completely with databases which use locks. The database rolls back the
128 ········/// transaction of the victim, so the step can be repeated. Each step uses its own PersistenceManager
129 ········/// and changes the IterationState only after a successful save, so a repetition starts from scratch.
130 ········/// </remarks>
131 ········async Task RunStepAsync( IterationState s, string step, Func<Task> action, CancellationToken ct )
132 ········{
133 ············s.Step = step;
134 ············for (int attempt = 1; ; attempt++)
135 ············{
136 ················try
137 ················{
138 ····················await action();
139 ····················return;
140 ················}
141 ················catch (Exception ex) when (attempt <= this.options.DeadlockRetries && !ct.IsCancellationRequested && IsDeadlock( ex ))
142 ················{
143 ····················this.statistics.DeadlockRetried( step );
144 ····················// A random delay, so that the competing transactions don't collide again
145 ····················await Task.Delay( this.random.Next( 10, 50 ) * attempt, ct );
146 ················}
147 ············}
148 ········}
149
150 ········/// <summary>
151 ········/// Checks, if an exception was caused by a deadlock.
152 ········/// </summary>
153 ········/// <remarks>
154 ········/// NDO wraps the exceptions of the ADO.NET providers in NDOExceptions. Versions up to 6.0.0 don't pass the original
155 ········/// exception as inner exception. Therefore the messages are checked as well. All supported databases mention "deadlock"
156 ········/// in their messages (SqlServer 1205, MySql 1213, Postgre 40P01). Sqlite doesn't have deadlocks.
157 ········/// </remarks>
158 ········static bool IsDeadlock( Exception ex )
159 ········{
160 ············for (Exception e = ex; e != null; e = e.InnerException)
161 ············{
162 if ( e is DbException dbe && ( dbe. SqlState == "40001" || dbe. SqlState == "40P01") )
163 return true;
164 if ( e. Message. IndexOf( "deadlock", StringComparison. OrdinalIgnoreCase ) >= 0)
165 return true;
166 }
167 return false;
 
 
 
 
 
 
168 ········}
169
170 ········/// <summary>
171 ········/// Creates a customer and an order with lines and two tags.
172 ········/// </summary>
173 ········async Task CreateAsync( IterationState s, CancellationToken ct )
174 ········{
175 ············await using (var pm = this.db.NewPersistenceManager())
176 ············{
177 ················var customer = new Customer()
178 ················{
179 ····················Name = s.CustomerName,
180 ····················City = "City" + this.workerNo,
181 ····················// Some databases don't store fractions of seconds
182 ····················Created = new DateTime( 2026, 1, 1, 12, 0, 0 ).AddMinutes( this.workerNo )
183 ················};
184
185 ················var order = new SalesOrder()
186 ················{
187 ····················OrderNumber = s.OrderNumber,
188 ····················OrderDate = DateTime.Today,
189 ····················Status = "New",
190 ····················Customer = customer
191 ················};
192
193 ················for (int i = 0; i < this.options.LinesPerOrder; i++)
194 ····················order.NewLine( "Product" + i, i + 1, 1.25m * (i + 1) );
195 ················order.Total = order.ComputeTotal();
196
197 ················// FindObject creates hollow objects without database access
198 ················var tagIndexes = PickDistinct( 2 );
199 ················foreach (int index in tagIndexes)
200 ····················order.AddTag( (Tag) pm.FindObject( typeof( Tag ), this.tagIds[index] ) );
201
202 ················pm.MakePersistent( customer );
203 ················pm.MakePersistent( order );
204 ················await this.statistics.MeasureAsync( "SaveAsync (insert)", () => pm.SaveAsync( false, ct ) );
205
206 ················s.OrderId = IdOf( order );
207 ················Check( s.OrderId > 0, $"Order {s.OrderNumber} didn't get an id." );
208 ················Check( order.Lines.All( l => IdOf( l ) > 0 ), $"Not all lines of order {s.OrderNumber} got an id." );
209 ················s.ExpectedTagIds = new HashSet<int>( tagIndexes.Select( i => this.tagIds[i] ) );
210 ············}
211 ········}
212
213 ········/// <summary>
214 ········/// Reads the order, changes fields, lines, tags and the customer and saves the changes.
215 ········/// </summary>
216 ········async Task ChangeAsync( IterationState s, CancellationToken ct )
217 ········{
218 ············await using (var pm = this.db.NewPersistenceManager())
219 ············{
220 ················var order = await this.statistics.MeasureAsync( "VirtualTable.SingleAsync",
221 ····················() => pm.Objects<SalesOrder>().Where( o => o.OrderNumber == s.OrderNumber ).SingleAsync( ct ) );
222 ················Check( IdOf( order ) == s.OrderId, $"Order {s.OrderNumber}: wrong id {IdOf( order )}, expected {s.OrderId}." );
223
224 ················await this.statistics.MeasureAsync( "LoadRelationAsync", () => pm.LoadRelationAsync( order, "lines", false, ct ) );
225 ················await this.statistics.MeasureAsync( "LoadRelationAsync", () => pm.LoadRelationAsync( order, "tags", false, ct ) );
226 ················var lines = order.Lines.ToList();
227 ················Check( lines.Count == this.options.LinesPerOrder, $"Order {s.OrderNumber}: {lines.Count} lines read, expected {this.options.LinesPerOrder}." );
228 ················var tagIdsRead = new HashSet<int>( order.Tags.Select( IdOf ) );
229 ················Check( tagIdsRead.SetEquals( s.ExpectedTagIds ), $"Order {s.OrderNumber}: wrong tags [{String.Join( ",", tagIdsRead )}], expected [{String.Join( ",", s.ExpectedTagIds )}]." );
230
231 ················Customer customer = order.Customer;
232 ················Check( customer != null, $"Order {s.OrderNumber} has no customer." );
233 ················await this.statistics.MeasureAsync( "LoadDataAsync", () => pm.LoadDataAsync( customer, ct ) );
234 ················Check( customer.Name == s.CustomerName, $"Order {s.OrderNumber}: wrong customer '{customer.Name}', expected '{s.CustomerName}'." );
235
236 ················// Change fields, change a line, remove a line, add a line
237 ················order.Status = "Changed";
238 ················var first = lines.OrderBy( l => l.Product ).First();
239 ················first.Quantity += 10;
240 ················order.RemoveLine( lines.OrderBy( l => l.Product ).Last() );
241 ················order.NewLine( "Extra", 7, 3.5m );
242 ················order.Total = order.ComputeTotal();
243
244 ················// Replace one tag by another one
245 ················var removedTag = order.Tags.First();
246 ················order.RemoveTag( removedTag );
247 ················int newTagId = this.tagIds.First( id => !s.ExpectedTagIds.Contains( id ) );
248 ················order.AddTag( (Tag) pm.FindObject( typeof( Tag ), newTagId ) );
249
250 ················customer.UpdateCount++;
251
252 ················await this.statistics.MeasureAsync( "SaveAsync (update)", () => pm.SaveAsync( false, ct ) );
253
254 ················s.ExpectedTagIds.Remove( IdOf( removedTag ) );
255 ················s.ExpectedTagIds.Add( newTagId );
256 ················s.ExpectedLineCount = order.Lines.Count();
257 ················s.ExpectedPriceSum = order.Lines.Sum( l => l.Price );
258 ················s.ExpectedTotal = order.Total;
259 ············}
260 ········}
261
262 ········/// <summary>
263 ········/// Checks the changes with a new PersistenceManager.
264 ········/// </summary>
265 ········async Task VerifyAsync( IterationState s, CancellationToken ct )
266 ········{
267 ············await using (var pm = this.db.NewPersistenceManager())
268 ············{
269 ················int orderId = s.OrderId;
270 ················var lineQuery = pm.Objects<OrderLine>().Where( l => l.Order.Oid() == orderId );
271
272 ················var lines = await this.statistics.MeasureAsync( "VirtualTable.ToListAsync", () => lineQuery.ToListAsync( ct ) );
273 ················Check( lines.Count == s.ExpectedLineCount, $"Order {s.OrderNumber}: {lines.Count} lines found, expected {s.ExpectedLineCount}." );
274 ················Check( lines.Any( l => l.Product == "Extra" ), $"Order {s.OrderNumber}: the added line is missing." );
275 ················Check( !lines.Any( l => l.Product == "Product" + (this.options.LinesPerOrder - 1) ), $"Order {s.OrderNumber}: the removed line still exists." );
276
277 ················int count = await this.statistics.MeasureAsync( "VirtualTable.CountAsync", () => lineQuery.CountAsync( ct ) );
278 ················Check( count == s.ExpectedLineCount, $"Order {s.OrderNumber}: CountAsync returns {count}, expected {s.ExpectedLineCount}." );
279
280 ················// Note: Sum over an int field doesn't work, because NDO always computes sums as decimal and casts the result to TP
281 ················decimal priceSum = await this.statistics.MeasureAsync( "VirtualTable.SumAsync", () => lineQuery.SumAsync( l => l.Price, ct ) );
282 ················Check( priceSum == s.ExpectedPriceSum, $"Order {s.OrderNumber}: SumAsync returns {priceSum}, expected {s.ExpectedPriceSum}." );
283
284 ················// await foreach over a VirtualTable with a condition on a related object
285 ················string customerName = s.CustomerName;
286 ················var orders = await this.statistics.MeasureAsync( "VirtualTable await foreach", async () =>
287 ················{
288 ····················var result = new List<SalesOrder>();
289 ····················await foreach (var o in pm.Objects<SalesOrder>().Where( o => o.Customer.Name == customerName ).AsAsyncEnumerable( ct ))
290 ························result.Add( o );
291 ····················return result;
292 ················} );
293 ················Check( orders.Count == 1, $"Customer {customerName}: {orders.Count} orders found, expected 1." );
294
295 ················var order = orders[0];
296 ················Check( order.OrderNumber == s.OrderNumber, $"Customer {customerName}: wrong order {order.OrderNumber}, expected {s.OrderNumber}." );
297 ················Check( order.Status == "Changed", $"Order {s.OrderNumber}: status '{order.Status}', expected 'Changed'." );
298 ················Check( order.Total == s.ExpectedTotal, $"Order {s.OrderNumber}: total {order.Total}, expected {s.ExpectedTotal}." );
299 ················decimal linesTotal = lines.Sum( l => l.Quantity * l.Price );
300 ················Check( linesTotal == s.ExpectedTotal, $"Order {s.OrderNumber}: the lines sum up to {linesTotal}, expected {s.ExpectedTotal}." );
301
302 ················await this.statistics.MeasureAsync( "LoadRelationAsync", () => pm.LoadRelationAsync( order, "tags", false, ct ) );
303 ················var tagIdsRead = new HashSet<int>( order.Tags.Select( IdOf ) );
304 ················Check( tagIdsRead.SetEquals( s.ExpectedTagIds ), $"Order {s.OrderNumber}: wrong tags [{String.Join( ",", tagIdsRead )}], expected [{String.Join( ",", s.ExpectedTagIds )}]." );
305
306 ················var customer = await this.statistics.MeasureAsync( "VirtualTable.FirstOrDefaultAsync",
307 ····················() => pm.Objects<Customer>().Where( c => c.Name == customerName ).FirstOrDefaultAsync( ct ) );
308 ················Check( customer != null, $"Customer {customerName} not found." );
309 ················Check( customer.UpdateCount == 1, $"Customer {customerName}: UpdateCount is {customer.UpdateCount}, expected 1." );
310
311 ················// RefreshAsync reads the object again
312 ················await this.statistics.MeasureAsync( "RefreshAsync", () => pm.RefreshAsync( customer, ct ) );
313 ················Check( customer.UpdateCount == 1, $"Customer {customerName}: UpdateCount after RefreshAsync is {customer.UpdateCount}, expected 1." );
314 ············}
315 ········}
316
317 ········/// <summary>
318 ········/// Queries, which read data of other workers. The results can't be checked, because the other workers change the data.
319 ········/// </summary>
320 ········async Task QueryAsync( CancellationToken ct )
321 ········{
322 ············await using (var pm = this.db.NewPersistenceManager())
323 ············{
324 ················await this.statistics.MeasureAsync( "VirtualTable.CountAsync", () => pm.Objects<SalesOrder>().Where( o => o.Status == "Changed" ).CountAsync( ct ) );
325 ················var page = await this.statistics.MeasureAsync( "VirtualTable paged",
326 ····················() => pm.Objects<SalesOrder>().OrderByDescending( o => o.OrderNumber ).Take( 10 ).ToListAsync( ct ) );
327 ················Check( page.Count <= 10, $"Take(10) returned {page.Count} objects." );
328 ················int tagCount = await this.statistics.MeasureAsync( "VirtualTable.CountAsync", () => pm.Objects<Tag>().CountAsync( ct ) );
329 ················Check( tagCount == this.tagIds.Length, $"{tagCount} tags found, expected {this.tagIds.Length}." );
330 ············}
331 ········}
332
333 ········/// <summary>
334 /// Deletes the order with PersistenceManager. Delete ( the composite relation deletes the lines and the mapping table entries) .
 
335 ········/// </summary>
336 async Task DeleteOrderAsync( IterationState s, CancellationToken ct )
337 ········{
338 ············await using (var pm = this.db.NewPersistenceManager())
339 ············{
340 ················var order = await this.statistics.MeasureAsync( "VirtualTable.SingleAsync",
341 ····················() => pm.Objects<SalesOrder>().Where( o => o.OrderNumber == s.OrderNumber ).SingleAsync( ct ) );
342 ················pm.Delete( order );
343 ················await this.statistics.MeasureAsync( "SaveAsync (delete)", () => pm.SaveAsync( false, ct ) );
344 ············}
345 ········}
346
347 ········/// <summary>
348 ········/// Deletes the customer with VirtualTable.DeleteDirectlyAsync.
349 ········/// </summary>
350 ········async Task DeleteCustomerAsync( IterationState s, CancellationToken ct )
351 ········{
352 ············await using (var pm = this.db.NewPersistenceManager())
353 ············{
354 ················string customerName = s.CustomerName;
355 ················await this.statistics.MeasureAsync( "VirtualTable.DeleteDirectlyAsync",
356 ····················() => pm.Objects<Customer>().Where( c => c.Name == customerName ).DeleteDirectlyAsync( ct ) );
357 ············}
358 ········}
359
360 ········async Task VerifyDeletionAsync( IterationState s, CancellationToken ct )
361 ········{
362 ············await using (var pm = this.db.NewPersistenceManager())
363 ············{
364 ················string orderNumber = s.OrderNumber;
365 ················string customerName = s.CustomerName;
366 ················int orderId = s.OrderId;
367
368 ················int orders = await pm.Objects<SalesOrder>().Where( o => o.OrderNumber == orderNumber ).CountAsync( ct );
369 ················Check( orders == 0, $"Order {orderNumber} still exists after deletion." );
370 ················int lines = await pm.Objects<OrderLine>().Where( l => l.Order.Oid() == orderId ).CountAsync( ct );
371 ················Check( lines == 0, $"Order {orderNumber}: {lines} lines still exist after deletion." );
372 ················int customers = await pm.Objects<Customer>().Where( c => c.Name == customerName ).CountAsync( ct );
373 ················Check( customers == 0, $"Customer {customerName} still exists after DeleteDirectlyAsync." );
374 ············}
375 ········}
376
377 ········int[] PickDistinct( int count )
378 ········{
379 ············return Enumerable.Range( 0, this.tagIds.Length ).OrderBy( _ => this.random.Next() ).Take( count ).ToArray();
380 ········}
381 ····}
382 }
383