Datei: NDODLL/Query/NDOQuery.cs

Last Commit (a4bc8a0)
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Linq;
5 using System.Text;
6 using NDOql;
7 using NDOql.Expressions;
8 using NDO.Mapping;
9 using System.Data;
10 using NDOInterfaces;
11 using System.Text.RegularExpressions;
12 using NDO.Linq;
13 using LE=System.Linq.Expressions;
14 using NDO.SqlPersistenceHandling;
15 using System.IO;
16 using System.Security.Cryptography;
17 using Microsoft.Extensions.DependencyInjection;
18
19 namespace NDO.Query
20 {
21 ····internal class FieldMarker
22 ····{
23 ········public static string Instance
24 ········{
25 ············get { return "##FIELDS##"; }
26 ········}
27 ····}
28
29 ····/// <summary>
30 ····/// This class manages string based queries in NDOql and Sql
31 ····/// </summary>
32 ····/// <typeparam name="T"></typeparam>
33 ····public class NDOQuery<T> : IQuery
34 ····{
35 ········private PersistenceManager pm;
36 ········private string queryExpression;
37 ········private bool hollowResults;
38 ········private QueryLanguage queryLanguage;
39 ········private Type resultType = typeof( T );
40 ········private bool allowSubclasses = true;
41 ········private OqlExpression expressionTree;
42 ········private List<QueryOrder> orderings = new List<QueryOrder>();
43 ········private List<QueryContextsEntry> queryContextsForTypes = null;
44 ········private Mappings mappings;
45 ········private List<object> parameters = new List<object>();
46 ········private List<string> prefetches = new List<string>();
47 ········private int skip;
48 ········private int take;
49
50 ········internal bool UseQueryCache => this.pm.UseQueryCache;
51 ········internal Dictionary<string, object> QueryCache => this.pm.QueryCache;
52
53
54 ········/// <summary>
55 ········/// Constructs a NDOQuery object
56 ········/// </summary>
57 ········/// <param name="pm">The PersistenceManager used to manage the objects.</param>
58 ········/// <remarks>
59 ········/// The query will return all available objects of the given type and it's subtypes.
60 ········/// The objects won't be hollow.
61 ········/// </remarks>
62 ········public NDOQuery( PersistenceManager pm )
63 ············: this( pm, null )
64 ········{
65 ········}
66
67 ········/// <summary>
68 ········/// Constructs a NDOQuery object
69 ········/// </summary>
70 ········/// <param name="pm">The PersistenceManager used to manage the objects.</param>
71 ········/// <param name="queryExpression">A NDOql expression.</param>
72 ········/// <remarks>
73 ········/// The query will return all available objects of the given
74 ········/// type and it's subtypes where the expression applies.
75 ········/// The objects won't be hollow.
76 ········/// </remarks>
77 ········public NDOQuery( PersistenceManager pm, string queryExpression )
78 ············: this( pm, queryExpression, false )
79 ········{
80 ········}
81
82 ········/// <summary>
83 ········/// Constructs a NDOQuery object
84 ········/// </summary>
85 ········/// <param name="pm">The PersistenceManager used to manage the objects.</param>
86 ········/// <param name="queryExpression">A NDOql expression.</param>
87 ········/// <param name="hollowResults">Determines, if the objects should be fetched in the hollow state (true) or filled with data (false).</param>
88 ········public NDOQuery( PersistenceManager pm, string queryExpression, bool hollowResults )
89 ············: this( pm, queryExpression, hollowResults, QueryLanguage.NDOql )
90 ········{
91 ········}
92
93 ········/// <summary>
94 ········/// Constructs a NDOQuery object
95 ········/// </summary>
96 ········/// <param name="pm">The PersistenceManager used to manage the objects.</param>
97 ········/// <param name="queryExpression">A NDOql or SQL expression.</param>
98 ········/// <param name="hollowResults">Determines, if the objects should be fetched in the hollow state (true) or filled with data (false).</param>
99 ········/// <param name="queryLanguage">Determines, if the query is a SQL pass-through query or a NDOql expression.</param>
100 ········public NDOQuery( PersistenceManager pm, string queryExpression, bool hollowResults, QueryLanguage queryLanguage )
101 ········{
102 ············if (pm.IsClosed)
103 throw new ObjectDisposedException( GetType( ) . Name ) ;
104
105 ············this.pm = pm;
106 ············if (pm == null)
107 ················throw new ArgumentException( "Parameter is null", "pm" );
108 ············this.mappings = pm.mappings;
109 ············this.queryExpression = queryExpression;
110 ············this.hollowResults = hollowResults;
111 ············this.queryLanguage = queryLanguage;
112 ········}
113
114 ········/// <summary>
115 ········/// Execute an aggregation query.
116 ········/// </summary>
117 ········/// <typeparam name="K"></typeparam>
118 ········/// <param name="keySelector">A Lambda expression which represents an accessor property of the field which shoule be aggregated.</param>
119 ········/// <param name="aggregateType">One of the <see cref="AggregateType">AggregateType</see> enum members.</param>
120 ········/// <returns>A single value, which represents the aggregate</returns>
121 ········/// <remarks>Before using this function, make shure, that your database product supports the aggregate function, as defined in aggregateType.
122 ········/// Polymorphy: StDev and Var only return the aggregate for the given class. All others return the aggregate for all subclasses.
123 ········/// Transactions: Please note, that the aggregate functions always work against the database.
124 ········/// Unsaved changes in your objects are not recognized.</remarks>
125 ········public object ExecuteAggregate<K>( LE.Expression<Func<T, K>> keySelector, AggregateType aggregateType )
126 ········{
127 ············ExpressionTreeTransformer transformer =
128 ················new ExpressionTreeTransformer( keySelector );
129 ············string field = transformer.Transform();
130 ············return ExecuteAggregate( field, aggregateType );
131 ········}
132
133 ········/// <summary>
134 ········/// Execute an aggregation query.
135 ········/// </summary>
136 ········/// <param name="aggregateType">One of the <see cref="AggregateType">AggregateType</see> enum members.</param>
137 ········/// <returns>A single value, which represents the aggregate</returns>
138 ········/// <remarks>Before using this function, make sure, that your database product supports the aggregate function, as defined in aggregateType.
139 ········/// Polymorphy: StDev and Var only return the aggregate for the given class. All others return the aggregate for all subclasses.
140 ········/// Transactions: Please note, that the aggregate functions always work against the database.
141 ········/// Unsaved changes in your objects are not recognized.</remarks>
142 ········public object ExecuteAggregate( AggregateType aggregateType )
143 ········{
144 ············return ExecuteAggregate( "*", aggregateType );
145 ········}
146
147 ········/// <summary>
148 ········/// Execute an aggregation query.
149 ········/// </summary>
150 ········/// <param name="field">The field, which should be aggregated</param>
151 ········/// <param name="aggregateType">One of the <see cref="AggregateType">AggregateType</see> enum members.</param>
152 ········/// <returns>A single value, which represents the aggregate</returns>
153 ········/// <remarks>Before using this function, make sure, that your database product supports the aggregate function, as defined in aggregateType.
154 ········/// Polymorphy: StDev and Var only return the aggregate for the given class. All others return the aggregate for all subclasses.
155 ········/// Transactions: Please note, that the aggregate functions always work against the database.
156 ········/// Unsaved changes in your objects are not recognized.</remarks>
157 ········public object ExecuteAggregate( string field, AggregateType aggregateType )
158 ········{
159 ············if (aggregateType == AggregateType.StDev || aggregateType == AggregateType.Var)
160 ················this.allowSubclasses = false;
161 ············if (this.queryContextsForTypes == null)
162 ················GenerateQueryContexts();
163
164 ············object[] partResults = new object[this.queryContextsForTypes.Count];
165
166 ············AggregateFunction func = new AggregateFunction( aggregateType );
167
168 ············int i = 0;
169 ············foreach (var queryContextsEntry in this.queryContextsForTypes)
170 ············{
171 ················partResults[i++] = ExecuteAggregateQuery( queryContextsEntry, field, aggregateType );
172 ············}
173 ············this.pm.CheckEndTransaction( !this.pm.DeferredMode && this.pm.TransactionMode == TransactionMode.Optimistic );
174 ············return func.ComputeResult( partResults );
175 ········}
176
177 ········/// <summary>
178 ········/// Deletes records directly without caring for composite relations.
179 ········/// </summary>
180 ········/// <remarks>Only use this method if your class does not use composite relations and you are sure that this will not be the case in the future either. If you are unsure about this, you better use PersistenceManager.Delete().</remarks>
181 ········public void DeleteDirectly()
182 ········{
183 ············string sql = GetDirectDeleteQuery();
184
185 ············using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( this.resultType ))
186 ············{
187 ················this.pm.CheckTransaction( persistenceHandler, this.resultType );
188 ················persistenceHandler.ExecuteBatch( new string[] { sql }, this.parameters );
189 ················this.pm.CheckEndTransaction( true );
190 ············}
191
192 ············//using (var handler = this.pm.GetSqlPassThroughHandler())
193 ············//{
194 ············//····handler.Execute( sql, false, this.parameters.ToArray() );
195 ············//····pm.Save(); // Commit
196 ············//}
197 ········}
198
199 ········/// <summary>
200 ········/// Computes the query used for DeleteDirectly().
201 ········/// </summary>
202 ········/// <returns></returns>
203 ········public string GetDirectDeleteQuery()
204 ········{
205 ············var queryString = GeneratedQuery;
206 ············if (queryString.IndexOf( "UNION" ) > -1)
207 ················throw new QueryException( 10052, $"This kind of query doesn't support {nameof(DeleteDirectly)}(). Please use pm.Delete(yourQueryResults)." );
208
209 ············var p = queryString.IndexOf( "FROM" );
210 ············if (p == -1)
211 ················throw new QueryException( 10051, $"Can't find 'FROM' in generated query. It seems, as if your query doesn't support {nameof( DeleteDirectly )}()." );
212
213 ············var sql = "DELETE " + queryString.Substring( p );
214
215 ············return sql;
216 ········}
217
218 ········private string GetSha()
219 ········{
220 ············MemoryStream ms = new MemoryStream();
221 ············var sw = new StreamWriter(ms);
222
223 ············sw.Write( typeof( T ).FullName );
224 ············sw.Write( '|' );
225 ············
226 ············foreach (var item in parameters)
227 ············{
228 ················if (item is byte[] bytes)
229 ················{
230 ····················foreach (var b in bytes)
231 ····················{
232 ························sw.Write( b );
233 ····················}
234 ····················sw.Write( '|' );
235 ················}
236 ················else
237 ················{
238 ····················sw.Write( item );
239 ····················sw.Write( '|' );
240 ················}
241 ············}
242
243 ············foreach (var item in orderings)
244 ············{
245 ················sw.Write( item.FieldName );
246 ················sw.Write( item.IsAscending );
247 ················sw.Write( '|' );
248 ············}
249
250 ············foreach (var item in prefetches)
251 ············{
252 ················sw.Write( item );
253 ················sw.Write( '|' );
254 ············}
255
256 ············sw.Write( $"skip{this.skip}|" );
257 ············sw.Write( $"take{this.take}" );
258
259 ············sw.Flush();
260 ············ms.Seek( 0L, SeekOrigin.Begin );
261 ············var sr = new StreamReader(ms);
262 ············var q = (this.queryExpression ?? "") + '|' + sr.ReadToEnd();
263 ············var qbytes = Encoding.UTF8.GetBytes(q);
264 ············var sha = SHA256.Create();
265 ············var hash = sha.ComputeHash( qbytes );
266 ············return Convert.ToBase64String( hash );
267 ········}
268
269 ········/// <summary>
270 ········/// Executes the query and returns a list of result objects.
271 ········/// </summary>
272 ········/// <returns></returns>
273 ········public List<T> Execute()
274 ········{
275 ············string sha = null;
276 ············if (UseQueryCache)
277 ············{
278 ················sha = GetSha();
279 ················if (QueryCache.ContainsKey( sha ))
280 ················{
281 ····················this.pm.LogIfVerbose( "Getting results from QueryCache" );
282 ····················return (List<T>) QueryCache[sha];
283 ················}
284 ············}
285
286 ············var result = GetResultList();
287
288 ············if (UseQueryCache)
289 ············{
290 ················QueryCache[sha] = result;
291 ············}
292
293 ············return result;
294 ········}
295
296 ········/// <summary>
297 ········/// Retrieves the SQL code of a NDOql Query.
298 ········/// </summary>
299 ········public string GeneratedQuery
300 ········{
301 ············get
302 ············{
303 ················if (this.queryLanguage == QueryLanguage.Sql)
304 ················{
305 ····················return this.queryExpression;
306 ················}
307
308 ················if (this.queryContextsForTypes == null)
309 ····················GenerateQueryContexts();
310
311 ················PrepareParameters();
312 ················IQueryGenerator queryGenerator = ServiceProvider.GetRequiredService<IQueryGenerator>().Initialize(this.mappings);
313 ················return queryGenerator.GenerateQueryStringForAllTypes( this.queryContextsForTypes, this.expressionTree, this.hollowResults, this.orderings, this.skip, this.take );
314 ············}
315 ········}
316
317 ········private List<T> GetResultList()
318 ········{
319 ············List<T> result = new List<T>();
320
321 ············GenerateQueryContexts();
322
323 ············// this.pm.CheckTransaction happens in ExecuteOrderedSubQuery or in ExecuteSubQuery
324
325 ············if (this.queryContextsForTypes.Count > 1 && this.orderings.Count > 0)
326 ············{
327 ················result = QueryOrderedPolymorphicList();
328 ············}
329 ············else
330 ············{
331 ················foreach (var queryContextsEntry in this.queryContextsForTypes)
332 ················{
333 ····················foreach (var item in ExecuteSubQuery( queryContextsEntry ))
334 ····················{
335 ························result.Add( item );
336 ····················}
337 ················}
338 ············}
339
340 ············//GetPrefetches( result );
341 ············this.pm.CheckEndTransaction( !this.pm.DeferredMode && this.pm.TransactionMode == TransactionMode.Optimistic );
342 ············if (!this.pm.GetClass( resultType ).Provider.SupportsFetchLimit)
343 ············{
344 ················List<T> fetchResult = new List<T>();
345 ················for (int i = this.skip; i < Math.Min( result.Count, i + this.take ); i++)
346 ····················fetchResult.Add( result[i] );
347 ············}
348 ············return result;
349 ········}
350
351 #if MaskOutPrefetches
352 ········Type GetPrefetchResultType( Type t, string relation )
353 ········{
354 ············string[] parts = relation.Split( '.' );
355 ············Class cl = pm.GetClass( t );
356 ············Relation rel = cl.FindRelation( parts[0] );
357 ············if (parts.Length == 1)
358 ················return rel.ReferencedType;
359 ············else
360 ················return GetPrefetchResultType( rel.ReferencedType,
361 ····················relation.Substring( relation.IndexOf( '.' ) + 1 ) );
362 ········}
363
364 ········void GetPrefetches( List<T> parents )
365 ········{
366 ············var queryGenerator = this.ConfigContainer.Resolve<IQueryGenerator>();
367 ············if (parents.Count == 0)
368 ················return;
369
370 ············var mustUseInClause = false;
371
372 ············if (this.expressionTree != null)
373 ················mustUseInClause = this.expressionTree.GetAll( n => n.Operator == "IN" ).Any();
374
375 ············foreach (string prefetch in this.Prefetches)
376 ············{
377 ················Type t = GetPrefetchResultType( this.resultType, prefetch );
378 ················using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( t ))
379 ················{
380 ····················persistenceHandler.VerboseMode = this.pm.VerboseMode;
381 ····················persistenceHandler.LogAdapter = this.pm.LogAdapter;
382 ····················DataTable table = null;
383 ····················foreach (var queryContextsEntry in this.queryContextsForTypes)
384 ····················{
385 ························Type parentType = queryContextsEntry.Type;
386 ························var parentCls = mappings.FindClass( parentType );
387 ························var isMultiple = parentCls.Oid.OidColumns.Count > 1;
388 ························var selectedParents = parents.Where( p => p.GetType() == parentType ).Select(p=>(IPersistenceCapable)p).ToList();
389 ························if (selectedParents.Count == 0)
390 ····························continue;
391
392 ························string generatedQuery;
393 ························if (!mustUseInClause && ( parents.Count > 100 || isMultiple ) && this.skip == 0 && this.take == 0)
394 ························{
395 ····························generatedQuery = queryGenerator.GenerateQueryString( queryContextsEntry, this.expressionTree, false, true, new List<QueryOrder>(), 0, 0, prefetch );
396 ························}
397 ························else
398 ························{
399 ····························if (isMultiple)
400 ································throw new QueryException( 10050, "Can't process a prefetch with skip, take & multiple oid columns" );
401 ····························generatedQuery = queryGenerator.GeneratePrefetchQuery( parentType, selectedParents, prefetch );
402 ························}
403 #warning Prefetches: Überprüfen, ob das in der normalen Transaktion mitläuft
404 ························//····················this.pm.CheckTransaction( persistenceHandler, t );
405
406 ························this.pm.CheckTransaction( persistenceHandler, t );
407
408 ························table = persistenceHandler.PerformQuery( generatedQuery, this.parameters, this.pm.DataSet );
409
410 ························var result = pm.DataTableToIList( t, table.Rows, false );
411 ························MatchRelations( parents, result, prefetch );
412 ····················}
413 ················}
414 ············}
415 ········}
416
417 ········void MatchRelations( List<T> parents, IList childs, string relationName )
418 ········{
419 ············if (parents.Count == 0)
420 ················return;
421 ············if (childs.Count == 0)
422 ················return;
423 ············Class cl = pm.GetClass( resultType );
424 ············Relation r = cl.FindRelation( relationName );
425 ············RelationCollector rc = new RelationCollector( cl );
426 ············rc.CollectRelations();
427 ············string[] parentColumns = rc.ForeignKeyColumns.ToArray();
428 ············cl = pm.GetClass( r.ReferencedType );
429 ············rc = new RelationCollector( cl );
430 ············rc.CollectRelations();
431 ············string[] childColumns = rc.ForeignKeyColumns.ToArray();
432 ············// Used to determine, if the relation has been collected
433 ············string testColumnName = r.ForeignKeyColumns.First().Name;
434 ············if (r.Multiplicity == RelationMultiplicity.Element && parentColumns.Contains( testColumnName ))
435 ············{
436 ················foreach (IPersistenceCapable parent in parents)
437 ················{
438 ····················foreach (IPersistenceCapable child in childs)
439 ····················{
440 ························if (parent.NDOLoadState.LostRowsEqualsOid( child.NDOObjectId.Id, r ))
441 ····························mappings.SetRelationField( parent, r.FieldName, child );
442 ························//KeyValuePair kvp = ((KeyValueList)parent.NDOLoadState.LostRowInfo)[r.ForeignKeyColumnName];
443 ························//if (kvp.Value.Equals(child.NDOObjectId.Id.Value))
444 ························//····mappings.SetRelationField(parent, r.FieldName, child);
445 ····················}
446 ················}
447 ············}
448 ············else if (r.Multiplicity == RelationMultiplicity.List && childColumns.Contains( testColumnName ))
449 ············{
450 ················foreach (IPersistenceCapable parent in parents)
451 ················{
452 ····················IList container = mappings.GetRelationContainer( parent, r );
453 ····················foreach (IPersistenceCapable child in childs)
454 ····················{
455 ························if (child.NDOLoadState.LostRowsEqualsOid( parent.NDOObjectId.Id, r ))
456 ····························container.Add( child );
457 ····················}
458
459 ····················parent.NDOSetLoadState( r.Ordinal, true );
460 ················}
461 ············}
462 ········}
463 #endif
464
465 ········private object ExecuteAggregateQuery( QueryContextsEntry queryContextsEntry, string field, AggregateType aggregateType )
466 ········{
467 ············Type t = queryContextsEntry.Type;
468 ············IQueryGenerator queryGenerator = ServiceProvider.GetRequiredService<IQueryGenerator>().Initialize(this.mappings);
469 ············string generatedQuery = queryGenerator.GenerateAggregateQueryString( field, queryContextsEntry, this.expressionTree, this.queryContextsForTypes.Count > 1, aggregateType );
470
471 ············using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( t ))
472 ············{
473 ················this.pm.CheckTransaction( persistenceHandler, t );
474
475 ················// Note, that we can't execute all subQueries in one batch, because
476 ················// the subqueries could be executed against different connections.
477 ················// TODO: This could be optimized, if we made clear whether the involved tables
478 ················// can be reached with the same connection.
479 ················var l = persistenceHandler.ExecuteBatch( new string[] { generatedQuery }, this.parameters );
480 ················if (l.Count == 0)
481 ····················return null;
482
483 ················return ( l[0] )["AggrResult"];
484 ············}
485 ········}
486
487 ········private List<T> ExecuteSqlQuery()
488 ········{
489 ············Type t = this.resultType;
490 ············using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( t ))
491 ············{
492 ················this.pm.CheckTransaction( persistenceHandler, t );
493 ················DataTable table = persistenceHandler.PerformQuery( this.queryExpression, this.parameters, this.pm.DataSet );
494 ················return (List<T>) pm.DataTableToIList( t, table.Rows, this.hollowResults );
495 ············}
496 ········}
497
498 ········private bool PrepareParameters()
499 ········{
500 ············if (this.expressionTree == null)
501 ················return false;
502 ············var expressions = this.expressionTree.GetAll( e => e is ParameterExpression ).Select( e => (ParameterExpression)e ).ToList();
503 ············if (expressions.Count == 0)
504 ················return true;
505 ············if (expressions[0].ParameterValue != null)
506 ················return false;
507 ············foreach (ParameterExpression item in expressions)
508 ············{
509 ················item.ParameterValue = this.parameters[item.Ordinal];
510 ············}
511
512 ············return true;
513 ········}
514
515 ········private void WriteBackParameters()
516 ········{
517 ············if (this.expressionTree == null)
518 ················return;
519 ············var expressions = this.expressionTree.GetAll( e => e is ParameterExpression ).Select( e => (ParameterExpression)e ).ToList();
520 ············if (expressions.Count == 0)
521 ················return;
522 ············var count = (from e in expressions select e.Ordinal).Max();
523 ············this.parameters = new List<object>( count );
524 ············for (int i = 0; i < count + 1; i++)
525 ················this.parameters.Add( null );
526 ············foreach (ParameterExpression item in expressions)
527 ············{
528 ················this.parameters[item.Ordinal] = item.ParameterValue;
529 ············}
530 ········}
531
532 ········private IList ExecuteSubQuery( Type t, QueryContextsEntry queryContextsEntry )
533 ········{
534 ············IQueryGenerator queryGenerator = ServiceProvider.GetRequiredService<IQueryGenerator>().Initialize(this.mappings);
535 ············bool hasBeenPrepared = PrepareParameters();
536 ············string generatedQuery;
537
538 ············if (this.queryLanguage == QueryLanguage.NDOql)
539 ················generatedQuery = queryGenerator.GenerateQueryString( queryContextsEntry, this.expressionTree, this.hollowResults, this.queryContextsForTypes.Count > 1, this.orderings, this.skip, this.take );
540 ············else
541 ················generatedQuery = (string)this.expressionTree.Value;
542
543 ············if (hasBeenPrepared)
544 ············{
545 ················WriteBackParameters();
546 ············}
547
548 ············using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( t ))
549 ············{
550 ················this.pm.CheckTransaction( persistenceHandler, t );
551
552 ················DataTable table = persistenceHandler.PerformQuery( generatedQuery, this.parameters, this.pm.DataSet );
553 ················return pm.DataTableToIList( t, table.Rows, this.hollowResults );
554 ············}
555 ········}
556
557 ········private IEnumerable<T> ExecuteSubQuery( QueryContextsEntry queryContextsEntry )
558 ········{
559 ············var subResult = ExecuteSubQuery( queryContextsEntry.Type, queryContextsEntry );
560 ············foreach (var item in subResult)
561 ············{
562 ················yield return (T)item;
563 ············}
564 ········}
565
566 ········private List<T> QueryOrderedPolymorphicList()
567 ········{
568 ············List<ObjectRowPair<T>> rowPairList = new List<ObjectRowPair<T>>();
569 ············foreach (var queryContextsEntry in this.queryContextsForTypes)
570 ················rowPairList.AddRange( ExecuteOrderedSubQuery( queryContextsEntry ) );
571 ············rowPairList.Sort();
572 ············List<T> result = new List<T>( rowPairList.Count );
573 ············foreach (ObjectRowPair<T> orp in rowPairList)
574 ················result.Add( (T)orp.Obj );
575 ············return result;
576 ········}
577
578 ········private List<ObjectRowPair<T>> ExecuteOrderedSubQuery( QueryContextsEntry queryContextsEntry )
579 ········{
580 ············Type t = queryContextsEntry.Type;
581 ············Class resultSubClass = this.pm.GetClass( t );
582 ············DataTable comparismTable = new DataTable( "ComparismTable" );
583 ············foreach (QueryOrder order in this.orderings)
584 ············{
585 ················DataColumn col = comparismTable.Columns.Add( order.FieldName );
586 ················if (order.IsAscending)
587 ····················col.AutoIncrementStep = 1;
588 ················else
589 ····················col.AutoIncrementStep = -1;
590 ············}
591
592 ············DataTable table = null;
593 ············using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( t ))
594 ············{
595 ················this.pm.CheckTransaction( persistenceHandler, t );
596
597 ················bool hasBeenPrepared = PrepareParameters();
598 ················IQueryGenerator queryGenerator = ServiceProvider.GetRequiredService<IQueryGenerator>().Initialize(this.mappings);
599 ················string generatedQuery = queryGenerator.GenerateQueryString( queryContextsEntry, this.expressionTree, this.hollowResults, this.queryContextsForTypes.Count > 1, this.orderings, this.skip, this.take );
600
601 ················if (hasBeenPrepared)
602 ················{
603 ····················WriteBackParameters();
604 ················}
605
606 ················table = persistenceHandler.PerformQuery( generatedQuery, this.parameters, this.pm.DataSet );
607 ············}
608
609 ············DataRow[] rows = table.Select();
610 ············var objects = pm.DataTableToIList( t, rows, this.hollowResults );
611 ············List<ObjectRowPair<T>> result = new List<ObjectRowPair<T>>( objects.Count );
612 ············int i = 0;
613 ············IProvider provider = mappings.GetProvider( t );
614 ············foreach (T obj in objects)
615 ············{
616 ················DataRow row = rows[i++];
617 ················DataRow newRow = comparismTable.NewRow();
618 ················foreach (QueryOrder order in this.orderings)
619 ················{
620 ····················string newColumnName = order.FieldName;
621 ····················if (!comparismTable.Columns.Contains( newColumnName ))
622 ························throw new InternalException( 558, "Query.cs - Column not found." );
623 ····················string oldColumnName = resultSubClass.FindField( order.FieldName ).Column.Name;
624 ····················if (!table.Columns.Contains( oldColumnName ))
625 ························throw new InternalException( 561, "Query.cs - Column not found." );
626 ····················newRow[newColumnName] = row[oldColumnName];
627 ················}
628 ················result.Add( new ObjectRowPair<T>( obj, newRow ) );
629 ············}
630
631 ············return result;
632 ········}
633
634
635 ········/// <summary>
636 ········/// Executes the query and returns a single object.
637 ········/// </summary>
638 ········/// <returns>The fetched object or null, if the object wasn't found. If the query has more than one result, the first of the results will be returned.</returns>
639 ········public T ExecuteSingle()
640 ········{
641 ············return ExecuteSingle( false );
642 ········}
643
644 ········/// <summary>
645 ········/// Executes the query and returns a single object.
646 ········/// </summary>
647 ········/// <param name="throwIfResultCountIsWrong"></param>
648 ········/// <returns>The fetched object or null, if the object wasn't found and throwIfResultCountIsWrong is false.</returns>
649 ········/// <remarks>
650 ········/// If throwIfResultCountIsWrong is true, an Exception will be throwed, if the result count isn't exactly 1.
651 ········/// If throwIfResultCountIsWrong is false and the query has more than one result, the first of the results will be returned.
652 ········/// </remarks>
653 ········public T ExecuteSingle( bool throwIfResultCountIsWrong )
654 ········{
655 ············var resultList = Execute();
656 ············int count = resultList.Count;
657 ············if (count == 1 || (!throwIfResultCountIsWrong && count > 0))
658 ············{
659 ················return resultList[0];
660 ············}
661 ············else
662 ············{
663 ················if (throwIfResultCountIsWrong)
664 ····················throw new QueryException( 10002, count.ToString() + " result objects in ExecuteSingle call" );
665 ················else
666 ····················return default( T );
667 ············}
668 ········}
669
670 ········/// <summary>
671 ········/// Constructs the subqueries necessary to fetch all objects of a
672 ········/// class and its subclasses.
673 ········/// </summary>
674 ········/// <remarks>
675 ········/// The function isn't actually recursive. The subclasses have been
676 ········/// recursively collected in NDOMapping.
677 ········/// </remarks>
678 ········private void CreateQueryContextsForTypes()
679 ········{
680 ············Dictionary<string, Type> usedTables = new Dictionary<string, Type>();
681 ············if (!resultType.IsAbstract)
682 ············{
683 ················Class cl = pm.GetClass( this.resultType );
684 ················usedTables.Add( cl.TableName, cl.SystemType );
685 ············}
686
687 ············if (this.allowSubclasses)
688 ············{
689 ················// Check if subclasses are mapped to the same table.
690 ················// Always fetch for the base class in the table
691 ················foreach (Class cl in pm.GetClass( resultType ).Subclasses)
692 ················{
693 ····················string tn = cl.TableName;
694 ····················if (usedTables.ContainsKey( tn ))
695 ····················{
696 ························Type t = (Type)usedTables[tn];
697 ························if (t.IsSubclassOf( cl.SystemType ))
698 ························{
699 ····························usedTables.Remove( tn );
700 ····························usedTables.Add( tn, cl.SystemType );
701 ························}
702 ························break;
703 ····················}
704 ····················usedTables.Add( tn, cl.SystemType );
705 ················}
706 ············}
707
708 ············var contextGenerator = new RelationContextGenerator(this.mappings);
709 ············this.queryContextsForTypes = new List<QueryContextsEntry>();
710 ············// usedTables now contains all assignable classes of our result type
711 ············foreach (var de in usedTables)
712 ············{
713 ················Type t2 = (Type)de.Value;
714 ················// Now we have to iterate through all mutations of
715 ················// polymorphic relations, used in the filter expression
716 ················var queryContexts = contextGenerator.GetContexts( this.pm.GetClass( t2 ), this.expressionTree );
717 ················this.queryContextsForTypes.Add( new QueryContextsEntry() { Type = t2, QueryContexts = queryContexts } );
718 ············}
719 ········}
720
721 ········private void GenerateQueryContexts()
722 ········{
723 ············//if ((int) this.queryLanguage == OldQuery.LoadRelations)
724 ············//····LoadRelatedTables();
725 ············//else if (this.queryLanguage == Language.NDOql)
726 ············if (this.queryLanguage == QueryLanguage.Sql)
727 ············{
728 ················var selectList = new SqlColumnListGenerator( pm.NDOMapping.FindClass( typeof( T ) ) ).SelectList;
729 ················var sql = Regex.Replace( this.queryExpression, @"SELECT\s+\*", "SELECT " + selectList );
730 ················this.expressionTree = new RawIdentifierExpression( sql, 0, 0 );
731 ············}
732 ············else
733 ············{
734 ················NDOql.OqlParser parser = new NDOql.OqlParser();
735 ················var parsedTree = parser.Parse( this.queryExpression );
736 ················if (parsedTree != null)
737 ················{
738 ····················// The root expression tree might get exchanged.
739 ····················// To make this possible we make it the child of a dummy expression.
740 ····················this.expressionTree = new OqlExpression( 0, 0 );
741 ····················this.expressionTree.Add( parsedTree );
742 ····················((IManageExpression)parsedTree).SetParent( this.expressionTree );
743 ················}
744 ············}
745
746 ············CreateQueryContextsForTypes();
747 ········}
748
749 ········IServiceProvider ServiceProvider
750 ········{
751 ············get { return this.pm.ServiceProvider; }
752 ········}
753
754 ········/// <summary>
755 ········/// Gets the query parameters
756 ········/// </summary>
757 ········public ICollection<object> Parameters
758 ········{
759 ············get { return this.parameters; }
760 ········}
761
762 ········/// <summary>
763 ········/// Indicates whether subclasses are allowed in the query
764 ········/// </summary>
765 ········public bool AllowSubclasses
766 ········{
767 ············get { return this.allowSubclasses; }
768 ············set { this.allowSubclasses = value; }
769 ········}
770
771 ········/// <summary>
772 ········/// Gets or sets the relations to be queried in the query
773 ········/// </summary>
774 ········public IEnumerable<string> Prefetches
775 ········{
776 ············get { return this.prefetches; }
777 ············set { this.prefetches = value.ToList(); }
778 ········}
779
780 ········/// <summary>
781 ········/// Gets or sets orderings
782 ········/// </summary>
783 ········public List<QueryOrder> Orderings
784 ········{
785 ············get { return this.orderings; }
786 ············set { this.orderings = value.ToList(); }
787 ········}
788
789 ········/// <summary>
790 ········/// Gets or sets the amount of elements to be skipped in an ordered query
791 ········/// </summary>
792 ········/// <remarks>This is for paging support.</remarks>
793 ········public int Skip
794 ········{
795 ············get { return this.skip; }
796 ············set { this.skip = value; }
797 ········}
798
799 ········/// <summary>
800 ········/// Gets or sets the amount of elements to be taken in an ordered query
801 ········/// </summary>
802 ········/// <remarks>This is for paging support.</remarks>
803 ········public int Take
804 ········{
805 ············get { return this.take; }
806 ············set { this.take = value; }
807 ········}
808
809 ········/// <summary>
810 ········/// Adds a prefetch to the query
811 ········/// </summary>
812 ········/// <param name="s"></param>
813 ········[Obsolete("Prefetches are not yet implemented, but will be in future.")]
814 ········public void AddPrefetch( string s )
815 ········{
816 ············this.prefetches.Add( s );
817 ········}
818
819 ········/// <summary>
820 ········/// Removes a prefetch from the query
821 ········/// </summary>
822 ········/// <param name="s"></param>
823 ········public void RemovePrefetch( string s )
824 ········{
825 ············if (this.prefetches.Contains( s ))
826 ················this.prefetches.Remove( s );
827 ········}
828
829 #region IQuery Interface
830
831 ········System.Collections.IList IQuery.Execute()
832 ········{
833 ············return this.Execute();
834 ········}
835
836 ········IPersistenceCapable IQuery.ExecuteSingle()
837 ········{
838 ············return (IPersistenceCapable)this.ExecuteSingle( false );
839 ········}
840
841 ········IPersistenceCapable IQuery.ExecuteSingle( bool throwIfResultCountIsWrong )
842 ········{
843 ············return (IPersistenceCapable)this.ExecuteSingle( throwIfResultCountIsWrong );
844 ········}
845
846 ········ICollection<object> IQuery.Parameters => this.parameters;
847 ········ICollection<QueryOrder> IQuery.Orderings => this.orderings;
848 ········object IQuery.ExecuteAggregate( string field, AggregateType aggregateType ) => ExecuteAggregate( field, aggregateType );
849 ········bool IQuery.AllowSubclasses { get => this.allowSubclasses; set => this.allowSubclasses = value; }
850 ········int IQuery.Skip { get => this.skip; set => this.skip = value; }
851 ········int IQuery.Take { get => this.take; set => this.take = value; }
852 ········string IQuery.GeneratedQuery { get { return this.GeneratedQuery; } }
853
854 #endregion
855
856 ····}
857 }
858
New Commit (0bf30ca)
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Linq;
5 using System.Text;
6 using NDOql;
7 using NDOql.Expressions;
8 using NDO.Mapping;
9 using System.Data;
10 using NDOInterfaces;
11 using System.Text.RegularExpressions;
12 using NDO.Linq;
13 using LE=System.Linq.Expressions;
14 using NDO.SqlPersistenceHandling;
15 using System.IO;
16 using System.Security.Cryptography;
17 using Microsoft.Extensions.DependencyInjection;
18
19 namespace NDO.Query
20 {
21 ····internal class FieldMarker
22 ····{
23 ········public static string Instance
24 ········{
25 ············get { return "##FIELDS##"; }
26 ········}
27 ····}
28
29 ····/// <summary>
30 ····/// This class manages string based queries in NDOql and Sql
31 ····/// </summary>
32 ····/// <typeparam name="T"></typeparam>
33 ····public class NDOQuery<T> : IQuery
34 ····{
35 ········private PersistenceManager pm;
36 ········private string queryExpression;
37 ········private bool hollowResults;
38 ········private QueryLanguage queryLanguage;
39 ········private Type resultType = typeof( T );
40 ········private bool allowSubclasses = true;
41 ········private OqlExpression expressionTree;
42 ········private List<QueryOrder> orderings = new List<QueryOrder>();
43 ········private List<QueryContextsEntry> queryContextsForTypes = null;
44 ········private Mappings mappings;
45 ········private List<object> parameters = new List<object>();
46 ········private List<string> prefetches = new List<string>();
47 ········private int skip;
48 ········private int take;
49
50 ········internal bool UseQueryCache => this.pm.UseQueryCache;
51 ········internal Dictionary<string, object> QueryCache => this.pm.QueryCache;
52
53
54 ········/// <summary>
55 ········/// Constructs a NDOQuery object
56 ········/// </summary>
57 ········/// <param name="pm">The PersistenceManager used to manage the objects.</param>
58 ········/// <remarks>
59 ········/// The query will return all available objects of the given type and it's subtypes.
60 ········/// The objects won't be hollow.
61 ········/// </remarks>
62 ········public NDOQuery( PersistenceManager pm )
63 ············: this( pm, null )
64 ········{
65 ········}
66
67 ········/// <summary>
68 ········/// Constructs a NDOQuery object
69 ········/// </summary>
70 ········/// <param name="pm">The PersistenceManager used to manage the objects.</param>
71 ········/// <param name="queryExpression">A NDOql expression.</param>
72 ········/// <remarks>
73 ········/// The query will return all available objects of the given
74 ········/// type and it's subtypes where the expression applies.
75 ········/// The objects won't be hollow.
76 ········/// </remarks>
77 ········public NDOQuery( PersistenceManager pm, string queryExpression )
78 ············: this( pm, queryExpression, false )
79 ········{
80 ········}
81
82 ········/// <summary>
83 ········/// Constructs a NDOQuery object
84 ········/// </summary>
85 ········/// <param name="pm">The PersistenceManager used to manage the objects.</param>
86 ········/// <param name="queryExpression">A NDOql expression.</param>
87 ········/// <param name="hollowResults">Determines, if the objects should be fetched in the hollow state (true) or filled with data (false).</param>
88 ········public NDOQuery( PersistenceManager pm, string queryExpression, bool hollowResults )
89 ············: this( pm, queryExpression, hollowResults, QueryLanguage.NDOql )
90 ········{
91 ········}
92
93 ········/// <summary>
94 ········/// Constructs a NDOQuery object
95 ········/// </summary>
96 ········/// <param name="pm">The PersistenceManager used to manage the objects.</param>
97 ········/// <param name="queryExpression">A NDOql or SQL expression.</param>
98 ········/// <param name="hollowResults">Determines, if the objects should be fetched in the hollow state (true) or filled with data (false).</param>
99 ········/// <param name="queryLanguage">Determines, if the query is a SQL pass-through query or a NDOql expression.</param>
100 ········public NDOQuery( PersistenceManager pm, string queryExpression, bool hollowResults, QueryLanguage queryLanguage )
101 ········{
102 ············if (pm.IsClosed)
103 throw new ObjectDisposedException( pm. GetType( ) . Name ) ;
104
105 ············this.pm = pm;
106 ············if (pm == null)
107 ················throw new ArgumentException( "Parameter is null", "pm" );
108 ············this.mappings = pm.mappings;
109 ············this.queryExpression = queryExpression;
110 ············this.hollowResults = hollowResults;
111 ············this.queryLanguage = queryLanguage;
112 ········}
113
114 ········/// <summary>
115 ········/// Execute an aggregation query.
116 ········/// </summary>
117 ········/// <typeparam name="K"></typeparam>
118 ········/// <param name="keySelector">A Lambda expression which represents an accessor property of the field which shoule be aggregated.</param>
119 ········/// <param name="aggregateType">One of the <see cref="AggregateType">AggregateType</see> enum members.</param>
120 ········/// <returns>A single value, which represents the aggregate</returns>
121 ········/// <remarks>Before using this function, make shure, that your database product supports the aggregate function, as defined in aggregateType.
122 ········/// Polymorphy: StDev and Var only return the aggregate for the given class. All others return the aggregate for all subclasses.
123 ········/// Transactions: Please note, that the aggregate functions always work against the database.
124 ········/// Unsaved changes in your objects are not recognized.</remarks>
125 ········public object ExecuteAggregate<K>( LE.Expression<Func<T, K>> keySelector, AggregateType aggregateType )
126 ········{
127 ············ExpressionTreeTransformer transformer =
128 ················new ExpressionTreeTransformer( keySelector );
129 ············string field = transformer.Transform();
130 ············return ExecuteAggregate( field, aggregateType );
131 ········}
132
133 ········/// <summary>
134 ········/// Execute an aggregation query.
135 ········/// </summary>
136 ········/// <param name="aggregateType">One of the <see cref="AggregateType">AggregateType</see> enum members.</param>
137 ········/// <returns>A single value, which represents the aggregate</returns>
138 ········/// <remarks>Before using this function, make sure, that your database product supports the aggregate function, as defined in aggregateType.
139 ········/// Polymorphy: StDev and Var only return the aggregate for the given class. All others return the aggregate for all subclasses.
140 ········/// Transactions: Please note, that the aggregate functions always work against the database.
141 ········/// Unsaved changes in your objects are not recognized.</remarks>
142 ········public object ExecuteAggregate( AggregateType aggregateType )
143 ········{
144 ············return ExecuteAggregate( "*", aggregateType );
145 ········}
146
147 ········/// <summary>
148 ········/// Execute an aggregation query.
149 ········/// </summary>
150 ········/// <param name="field">The field, which should be aggregated</param>
151 ········/// <param name="aggregateType">One of the <see cref="AggregateType">AggregateType</see> enum members.</param>
152 ········/// <returns>A single value, which represents the aggregate</returns>
153 ········/// <remarks>Before using this function, make sure, that your database product supports the aggregate function, as defined in aggregateType.
154 ········/// Polymorphy: StDev and Var only return the aggregate for the given class. All others return the aggregate for all subclasses.
155 ········/// Transactions: Please note, that the aggregate functions always work against the database.
156 ········/// Unsaved changes in your objects are not recognized.</remarks>
157 ········public object ExecuteAggregate( string field, AggregateType aggregateType )
158 ········{
159 ············if (aggregateType == AggregateType.StDev || aggregateType == AggregateType.Var)
160 ················this.allowSubclasses = false;
161 ············if (this.queryContextsForTypes == null)
162 ················GenerateQueryContexts();
163
164 ············object[] partResults = new object[this.queryContextsForTypes.Count];
165
166 ············AggregateFunction func = new AggregateFunction( aggregateType );
167
168 ············int i = 0;
169 ············foreach (var queryContextsEntry in this.queryContextsForTypes)
170 ············{
171 ················partResults[i++] = ExecuteAggregateQuery( queryContextsEntry, field, aggregateType );
172 ············}
173 ············this.pm.CheckEndTransaction( !this.pm.DeferredMode && this.pm.TransactionMode == TransactionMode.Optimistic );
174 ············return func.ComputeResult( partResults );
175 ········}
176
177 ········/// <summary>
178 ········/// Deletes records directly without caring for composite relations.
179 ········/// </summary>
180 ········/// <remarks>Only use this method if your class does not use composite relations and you are sure that this will not be the case in the future either. If you are unsure about this, you better use PersistenceManager.Delete().</remarks>
181 ········public void DeleteDirectly()
182 ········{
183 ············string sql = GetDirectDeleteQuery();
184
185 ············using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( this.resultType ))
186 ············{
187 ················this.pm.CheckTransaction( persistenceHandler, this.resultType );
188 ················persistenceHandler.ExecuteBatch( new string[] { sql }, this.parameters );
189 ················this.pm.CheckEndTransaction( true );
190 ············}
191
192 ············//using (var handler = this.pm.GetSqlPassThroughHandler())
193 ············//{
194 ············//····handler.Execute( sql, false, this.parameters.ToArray() );
195 ············//····pm.Save(); // Commit
196 ············//}
197 ········}
198
199 ········/// <summary>
200 ········/// Computes the query used for DeleteDirectly().
201 ········/// </summary>
202 ········/// <returns></returns>
203 ········public string GetDirectDeleteQuery()
204 ········{
205 ············var queryString = GeneratedQuery;
206 ············if (queryString.IndexOf( "UNION" ) > -1)
207 ················throw new QueryException( 10052, $"This kind of query doesn't support {nameof(DeleteDirectly)}(). Please use pm.Delete(yourQueryResults)." );
208
209 ············var p = queryString.IndexOf( "FROM" );
210 ············if (p == -1)
211 ················throw new QueryException( 10051, $"Can't find 'FROM' in generated query. It seems, as if your query doesn't support {nameof( DeleteDirectly )}()." );
212
213 ············var sql = "DELETE " + queryString.Substring( p );
214
215 ············return sql;
216 ········}
217
218 ········private string GetSha()
219 ········{
220 ············MemoryStream ms = new MemoryStream();
221 ············var sw = new StreamWriter(ms);
222
223 ············sw.Write( typeof( T ).FullName );
224 ············sw.Write( '|' );
225 ············
226 ············foreach (var item in parameters)
227 ············{
228 ················if (item is byte[] bytes)
229 ················{
230 ····················foreach (var b in bytes)
231 ····················{
232 ························sw.Write( b );
233 ····················}
234 ····················sw.Write( '|' );
235 ················}
236 ················else
237 ················{
238 ····················sw.Write( item );
239 ····················sw.Write( '|' );
240 ················}
241 ············}
242
243 ············foreach (var item in orderings)
244 ············{
245 ················sw.Write( item.FieldName );
246 ················sw.Write( item.IsAscending );
247 ················sw.Write( '|' );
248 ············}
249
250 ············foreach (var item in prefetches)
251 ············{
252 ················sw.Write( item );
253 ················sw.Write( '|' );
254 ············}
255
256 ············sw.Write( $"skip{this.skip}|" );
257 ············sw.Write( $"take{this.take}" );
258
259 ············sw.Flush();
260 ············ms.Seek( 0L, SeekOrigin.Begin );
261 ············var sr = new StreamReader(ms);
262 ············var q = (this.queryExpression ?? "") + '|' + sr.ReadToEnd();
263 ············var qbytes = Encoding.UTF8.GetBytes(q);
264 ············var sha = SHA256.Create();
265 ············var hash = sha.ComputeHash( qbytes );
266 ············return Convert.ToBase64String( hash );
267 ········}
268
269 ········/// <summary>
270 ········/// Executes the query and returns a list of result objects.
271 ········/// </summary>
272 ········/// <returns></returns>
273 ········public List<T> Execute()
274 ········{
275 ············string sha = null;
276 ············if (UseQueryCache)
277 ············{
278 ················sha = GetSha();
279 ················if (QueryCache.ContainsKey( sha ))
280 ················{
281 ····················this.pm.LogIfVerbose( "Getting results from QueryCache" );
282 ····················return (List<T>) QueryCache[sha];
283 ················}
284 ············}
285
286 ············var result = GetResultList();
287
288 ············if (UseQueryCache)
289 ············{
290 ················QueryCache[sha] = result;
291 ············}
292
293 ············return result;
294 ········}
295
296 ········/// <summary>
297 ········/// Retrieves the SQL code of a NDOql Query.
298 ········/// </summary>
299 ········public string GeneratedQuery
300 ········{
301 ············get
302 ············{
303 ················if (this.queryLanguage == QueryLanguage.Sql)
304 ················{
305 ····················return this.queryExpression;
306 ················}
307
308 ················if (this.queryContextsForTypes == null)
309 ····················GenerateQueryContexts();
310
311 ················PrepareParameters();
312 ················IQueryGenerator queryGenerator = ServiceProvider.GetRequiredService<IQueryGenerator>().Initialize(this.mappings);
313 ················return queryGenerator.GenerateQueryStringForAllTypes( this.queryContextsForTypes, this.expressionTree, this.hollowResults, this.orderings, this.skip, this.take );
314 ············}
315 ········}
316
317 ········private List<T> GetResultList()
318 ········{
319 ············List<T> result = new List<T>();
320
321 ············GenerateQueryContexts();
322
323 ············// this.pm.CheckTransaction happens in ExecuteOrderedSubQuery or in ExecuteSubQuery
324
325 ············if (this.queryContextsForTypes.Count > 1 && this.orderings.Count > 0)
326 ············{
327 ················result = QueryOrderedPolymorphicList();
328 ············}
329 ············else
330 ············{
331 ················foreach (var queryContextsEntry in this.queryContextsForTypes)
332 ················{
333 ····················foreach (var item in ExecuteSubQuery( queryContextsEntry ))
334 ····················{
335 ························result.Add( item );
336 ····················}
337 ················}
338 ············}
339
340 ············//GetPrefetches( result );
341 ············this.pm.CheckEndTransaction( !this.pm.DeferredMode && this.pm.TransactionMode == TransactionMode.Optimistic );
342 ············if (!this.pm.GetClass( resultType ).Provider.SupportsFetchLimit)
343 ············{
344 ················List<T> fetchResult = new List<T>();
345 ················for (int i = this.skip; i < Math.Min( result.Count, i + this.take ); i++)
346 ····················fetchResult.Add( result[i] );
347 ············}
348 ············return result;
349 ········}
350
351 #if MaskOutPrefetches
352 ········Type GetPrefetchResultType( Type t, string relation )
353 ········{
354 ············string[] parts = relation.Split( '.' );
355 ············Class cl = pm.GetClass( t );
356 ············Relation rel = cl.FindRelation( parts[0] );
357 ············if (parts.Length == 1)
358 ················return rel.ReferencedType;
359 ············else
360 ················return GetPrefetchResultType( rel.ReferencedType,
361 ····················relation.Substring( relation.IndexOf( '.' ) + 1 ) );
362 ········}
363
364 ········void GetPrefetches( List<T> parents )
365 ········{
366 ············var queryGenerator = this.ConfigContainer.Resolve<IQueryGenerator>();
367 ············if (parents.Count == 0)
368 ················return;
369
370 ············var mustUseInClause = false;
371
372 ············if (this.expressionTree != null)
373 ················mustUseInClause = this.expressionTree.GetAll( n => n.Operator == "IN" ).Any();
374
375 ············foreach (string prefetch in this.Prefetches)
376 ············{
377 ················Type t = GetPrefetchResultType( this.resultType, prefetch );
378 ················using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( t ))
379 ················{
380 ····················persistenceHandler.VerboseMode = this.pm.VerboseMode;
381 ····················persistenceHandler.LogAdapter = this.pm.LogAdapter;
382 ····················DataTable table = null;
383 ····················foreach (var queryContextsEntry in this.queryContextsForTypes)
384 ····················{
385 ························Type parentType = queryContextsEntry.Type;
386 ························var parentCls = mappings.FindClass( parentType );
387 ························var isMultiple = parentCls.Oid.OidColumns.Count > 1;
388 ························var selectedParents = parents.Where( p => p.GetType() == parentType ).Select(p=>(IPersistenceCapable)p).ToList();
389 ························if (selectedParents.Count == 0)
390 ····························continue;
391
392 ························string generatedQuery;
393 ························if (!mustUseInClause && ( parents.Count > 100 || isMultiple ) && this.skip == 0 && this.take == 0)
394 ························{
395 ····························generatedQuery = queryGenerator.GenerateQueryString( queryContextsEntry, this.expressionTree, false, true, new List<QueryOrder>(), 0, 0, prefetch );
396 ························}
397 ························else
398 ························{
399 ····························if (isMultiple)
400 ································throw new QueryException( 10050, "Can't process a prefetch with skip, take & multiple oid columns" );
401 ····························generatedQuery = queryGenerator.GeneratePrefetchQuery( parentType, selectedParents, prefetch );
402 ························}
403 #warning Prefetches: Überprüfen, ob das in der normalen Transaktion mitläuft
404 ························//····················this.pm.CheckTransaction( persistenceHandler, t );
405
406 ························this.pm.CheckTransaction( persistenceHandler, t );
407
408 ························table = persistenceHandler.PerformQuery( generatedQuery, this.parameters, this.pm.DataSet );
409
410 ························var result = pm.DataTableToIList( t, table.Rows, false );
411 ························MatchRelations( parents, result, prefetch );
412 ····················}
413 ················}
414 ············}
415 ········}
416
417 ········void MatchRelations( List<T> parents, IList childs, string relationName )
418 ········{
419 ············if (parents.Count == 0)
420 ················return;
421 ············if (childs.Count == 0)
422 ················return;
423 ············Class cl = pm.GetClass( resultType );
424 ············Relation r = cl.FindRelation( relationName );
425 ············RelationCollector rc = new RelationCollector( cl );
426 ············rc.CollectRelations();
427 ············string[] parentColumns = rc.ForeignKeyColumns.ToArray();
428 ············cl = pm.GetClass( r.ReferencedType );
429 ············rc = new RelationCollector( cl );
430 ············rc.CollectRelations();
431 ············string[] childColumns = rc.ForeignKeyColumns.ToArray();
432 ············// Used to determine, if the relation has been collected
433 ············string testColumnName = r.ForeignKeyColumns.First().Name;
434 ············if (r.Multiplicity == RelationMultiplicity.Element && parentColumns.Contains( testColumnName ))
435 ············{
436 ················foreach (IPersistenceCapable parent in parents)
437 ················{
438 ····················foreach (IPersistenceCapable child in childs)
439 ····················{
440 ························if (parent.NDOLoadState.LostRowsEqualsOid( child.NDOObjectId.Id, r ))
441 ····························mappings.SetRelationField( parent, r.FieldName, child );
442 ························//KeyValuePair kvp = ((KeyValueList)parent.NDOLoadState.LostRowInfo)[r.ForeignKeyColumnName];
443 ························//if (kvp.Value.Equals(child.NDOObjectId.Id.Value))
444 ························//····mappings.SetRelationField(parent, r.FieldName, child);
445 ····················}
446 ················}
447 ············}
448 ············else if (r.Multiplicity == RelationMultiplicity.List && childColumns.Contains( testColumnName ))
449 ············{
450 ················foreach (IPersistenceCapable parent in parents)
451 ················{
452 ····················IList container = mappings.GetRelationContainer( parent, r );
453 ····················foreach (IPersistenceCapable child in childs)
454 ····················{
455 ························if (child.NDOLoadState.LostRowsEqualsOid( parent.NDOObjectId.Id, r ))
456 ····························container.Add( child );
457 ····················}
458
459 ····················parent.NDOSetLoadState( r.Ordinal, true );
460 ················}
461 ············}
462 ········}
463 #endif
464
465 ········private object ExecuteAggregateQuery( QueryContextsEntry queryContextsEntry, string field, AggregateType aggregateType )
466 ········{
467 ············Type t = queryContextsEntry.Type;
468 ············IQueryGenerator queryGenerator = ServiceProvider.GetRequiredService<IQueryGenerator>().Initialize(this.mappings);
469 ············string generatedQuery = queryGenerator.GenerateAggregateQueryString( field, queryContextsEntry, this.expressionTree, this.queryContextsForTypes.Count > 1, aggregateType );
470
471 ············using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( t ))
472 ············{
473 ················this.pm.CheckTransaction( persistenceHandler, t );
474
475 ················// Note, that we can't execute all subQueries in one batch, because
476 ················// the subqueries could be executed against different connections.
477 ················// TODO: This could be optimized, if we made clear whether the involved tables
478 ················// can be reached with the same connection.
479 ················var l = persistenceHandler.ExecuteBatch( new string[] { generatedQuery }, this.parameters );
480 ················if (l.Count == 0)
481 ····················return null;
482
483 ················return ( l[0] )["AggrResult"];
484 ············}
485 ········}
486
487 ········private List<T> ExecuteSqlQuery()
488 ········{
489 ············Type t = this.resultType;
490 ············using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( t ))
491 ············{
492 ················this.pm.CheckTransaction( persistenceHandler, t );
493 ················DataTable table = persistenceHandler.PerformQuery( this.queryExpression, this.parameters, this.pm.DataSet );
494 ················return (List<T>) pm.DataTableToIList( t, table.Rows, this.hollowResults );
495 ············}
496 ········}
497
498 ········private bool PrepareParameters()
499 ········{
500 ············if (this.expressionTree == null)
501 ················return false;
502 ············var expressions = this.expressionTree.GetAll( e => e is ParameterExpression ).Select( e => (ParameterExpression)e ).ToList();
503 ············if (expressions.Count == 0)
504 ················return true;
505 ············if (expressions[0].ParameterValue != null)
506 ················return false;
507 ············foreach (ParameterExpression item in expressions)
508 ············{
509 ················item.ParameterValue = this.parameters[item.Ordinal];
510 ············}
511
512 ············return true;
513 ········}
514
515 ········private void WriteBackParameters()
516 ········{
517 ············if (this.expressionTree == null)
518 ················return;
519 ············var expressions = this.expressionTree.GetAll( e => e is ParameterExpression ).Select( e => (ParameterExpression)e ).ToList();
520 ············if (expressions.Count == 0)
521 ················return;
522 ············var count = (from e in expressions select e.Ordinal).Max();
523 ············this.parameters = new List<object>( count );
524 ············for (int i = 0; i < count + 1; i++)
525 ················this.parameters.Add( null );
526 ············foreach (ParameterExpression item in expressions)
527 ············{
528 ················this.parameters[item.Ordinal] = item.ParameterValue;
529 ············}
530 ········}
531
532 ········private IList ExecuteSubQuery( Type t, QueryContextsEntry queryContextsEntry )
533 ········{
534 ············IQueryGenerator queryGenerator = ServiceProvider.GetRequiredService<IQueryGenerator>().Initialize(this.mappings);
535 ············bool hasBeenPrepared = PrepareParameters();
536 ············string generatedQuery;
537
538 ············if (this.queryLanguage == QueryLanguage.NDOql)
539 ················generatedQuery = queryGenerator.GenerateQueryString( queryContextsEntry, this.expressionTree, this.hollowResults, this.queryContextsForTypes.Count > 1, this.orderings, this.skip, this.take );
540 ············else
541 ················generatedQuery = (string)this.expressionTree.Value;
542
543 ············if (hasBeenPrepared)
544 ············{
545 ················WriteBackParameters();
546 ············}
547
548 ············using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( t ))
549 ············{
550 ················this.pm.CheckTransaction( persistenceHandler, t );
551
552 ················DataTable table = persistenceHandler.PerformQuery( generatedQuery, this.parameters, this.pm.DataSet );
553 ················return pm.DataTableToIList( t, table.Rows, this.hollowResults );
554 ············}
555 ········}
556
557 ········private IEnumerable<T> ExecuteSubQuery( QueryContextsEntry queryContextsEntry )
558 ········{
559 ············var subResult = ExecuteSubQuery( queryContextsEntry.Type, queryContextsEntry );
560 ············foreach (var item in subResult)
561 ············{
562 ················yield return (T)item;
563 ············}
564 ········}
565
566 ········private List<T> QueryOrderedPolymorphicList()
567 ········{
568 ············List<ObjectRowPair<T>> rowPairList = new List<ObjectRowPair<T>>();
569 ············foreach (var queryContextsEntry in this.queryContextsForTypes)
570 ················rowPairList.AddRange( ExecuteOrderedSubQuery( queryContextsEntry ) );
571 ············rowPairList.Sort();
572 ············List<T> result = new List<T>( rowPairList.Count );
573 ············foreach (ObjectRowPair<T> orp in rowPairList)
574 ················result.Add( (T)orp.Obj );
575 ············return result;
576 ········}
577
578 ········private List<ObjectRowPair<T>> ExecuteOrderedSubQuery( QueryContextsEntry queryContextsEntry )
579 ········{
580 ············Type t = queryContextsEntry.Type;
581 ············Class resultSubClass = this.pm.GetClass( t );
582 ············DataTable comparismTable = new DataTable( "ComparismTable" );
583 ············foreach (QueryOrder order in this.orderings)
584 ············{
585 ················DataColumn col = comparismTable.Columns.Add( order.FieldName );
586 ················if (order.IsAscending)
587 ····················col.AutoIncrementStep = 1;
588 ················else
589 ····················col.AutoIncrementStep = -1;
590 ············}
591
592 ············DataTable table = null;
593 ············using (IPersistenceHandler persistenceHandler = this.pm.PersistenceHandlerManager.GetPersistenceHandler( t ))
594 ············{
595 ················this.pm.CheckTransaction( persistenceHandler, t );
596
597 ················bool hasBeenPrepared = PrepareParameters();
598 ················IQueryGenerator queryGenerator = ServiceProvider.GetRequiredService<IQueryGenerator>().Initialize(this.mappings);
599 ················string generatedQuery = queryGenerator.GenerateQueryString( queryContextsEntry, this.expressionTree, this.hollowResults, this.queryContextsForTypes.Count > 1, this.orderings, this.skip, this.take );
600
601 ················if (hasBeenPrepared)
602 ················{
603 ····················WriteBackParameters();
604 ················}
605
606 ················table = persistenceHandler.PerformQuery( generatedQuery, this.parameters, this.pm.DataSet );
607 ············}
608
609 ············DataRow[] rows = table.Select();
610 ············var objects = pm.DataTableToIList( t, rows, this.hollowResults );
611 ············List<ObjectRowPair<T>> result = new List<ObjectRowPair<T>>( objects.Count );
612 ············int i = 0;
613 ············IProvider provider = mappings.GetProvider( t );
614 ············foreach (T obj in objects)
615 ············{
616 ················DataRow row = rows[i++];
617 ················DataRow newRow = comparismTable.NewRow();
618 ················foreach (QueryOrder order in this.orderings)
619 ················{
620 ····················string newColumnName = order.FieldName;
621 ····················if (!comparismTable.Columns.Contains( newColumnName ))
622 ························throw new InternalException( 558, "Query.cs - Column not found." );
623 ····················string oldColumnName = resultSubClass.FindField( order.FieldName ).Column.Name;
624 ····················if (!table.Columns.Contains( oldColumnName ))
625 ························throw new InternalException( 561, "Query.cs - Column not found." );
626 ····················newRow[newColumnName] = row[oldColumnName];
627 ················}
628 ················result.Add( new ObjectRowPair<T>( obj, newRow ) );
629 ············}
630
631 ············return result;
632 ········}
633
634
635 ········/// <summary>
636 ········/// Executes the query and returns a single object.
637 ········/// </summary>
638 ········/// <returns>The fetched object or null, if the object wasn't found. If the query has more than one result, the first of the results will be returned.</returns>
639 ········public T ExecuteSingle()
640 ········{
641 ············return ExecuteSingle( false );
642 ········}
643
644 ········/// <summary>
645 ········/// Executes the query and returns a single object.
646 ········/// </summary>
647 ········/// <param name="throwIfResultCountIsWrong"></param>
648 ········/// <returns>The fetched object or null, if the object wasn't found and throwIfResultCountIsWrong is false.</returns>
649 ········/// <remarks>
650 ········/// If throwIfResultCountIsWrong is true, an Exception will be throwed, if the result count isn't exactly 1.
651 ········/// If throwIfResultCountIsWrong is false and the query has more than one result, the first of the results will be returned.
652 ········/// </remarks>
653 ········public T ExecuteSingle( bool throwIfResultCountIsWrong )
654 ········{
655 ············var resultList = Execute();
656 ············int count = resultList.Count;
657 ············if (count == 1 || (!throwIfResultCountIsWrong && count > 0))
658 ············{
659 ················return resultList[0];
660 ············}
661 ············else
662 ············{
663 ················if (throwIfResultCountIsWrong)
664 ····················throw new QueryException( 10002, count.ToString() + " result objects in ExecuteSingle call" );
665 ················else
666 ····················return default( T );
667 ············}
668 ········}
669
670 ········/// <summary>
671 ········/// Constructs the subqueries necessary to fetch all objects of a
672 ········/// class and its subclasses.
673 ········/// </summary>
674 ········/// <remarks>
675 ········/// The function isn't actually recursive. The subclasses have been
676 ········/// recursively collected in NDOMapping.
677 ········/// </remarks>
678 ········private void CreateQueryContextsForTypes()
679 ········{
680 ············Dictionary<string, Type> usedTables = new Dictionary<string, Type>();
681 ············if (!resultType.IsAbstract)
682 ············{
683 ················Class cl = pm.GetClass( this.resultType );
684 ················usedTables.Add( cl.TableName, cl.SystemType );
685 ············}
686
687 ············if (this.allowSubclasses)
688 ············{
689 ················// Check if subclasses are mapped to the same table.
690 ················// Always fetch for the base class in the table
691 ················foreach (Class cl in pm.GetClass( resultType ).Subclasses)
692 ················{
693 ····················string tn = cl.TableName;
694 ····················if (usedTables.ContainsKey( tn ))
695 ····················{
696 ························Type t = (Type)usedTables[tn];
697 ························if (t.IsSubclassOf( cl.SystemType ))
698 ························{
699 ····························usedTables.Remove( tn );
700 ····························usedTables.Add( tn, cl.SystemType );
701 ························}
702 ························break;
703 ····················}
704 ····················usedTables.Add( tn, cl.SystemType );
705 ················}
706 ············}
707
708 ············var contextGenerator = new RelationContextGenerator(this.mappings);
709 ············this.queryContextsForTypes = new List<QueryContextsEntry>();
710 ············// usedTables now contains all assignable classes of our result type
711 ············foreach (var de in usedTables)
712 ············{
713 ················Type t2 = (Type)de.Value;
714 ················// Now we have to iterate through all mutations of
715 ················// polymorphic relations, used in the filter expression
716 ················var queryContexts = contextGenerator.GetContexts( this.pm.GetClass( t2 ), this.expressionTree );
717 ················this.queryContextsForTypes.Add( new QueryContextsEntry() { Type = t2, QueryContexts = queryContexts } );
718 ············}
719 ········}
720
721 ········private void GenerateQueryContexts()
722 ········{
723 ············//if ((int) this.queryLanguage == OldQuery.LoadRelations)
724 ············//····LoadRelatedTables();
725 ············//else if (this.queryLanguage == Language.NDOql)
726 ············if (this.queryLanguage == QueryLanguage.Sql)
727 ············{
728 ················var selectList = new SqlColumnListGenerator( pm.NDOMapping.FindClass( typeof( T ) ) ).SelectList;
729 ················var sql = Regex.Replace( this.queryExpression, @"SELECT\s+\*", "SELECT " + selectList );
730 ················this.expressionTree = new RawIdentifierExpression( sql, 0, 0 );
731 ············}
732 ············else
733 ············{
734 ················NDOql.OqlParser parser = new NDOql.OqlParser();
735 ················var parsedTree = parser.Parse( this.queryExpression );
736 ················if (parsedTree != null)
737 ················{
738 ····················// The root expression tree might get exchanged.
739 ····················// To make this possible we make it the child of a dummy expression.
740 ····················this.expressionTree = new OqlExpression( 0, 0 );
741 ····················this.expressionTree.Add( parsedTree );
742 ····················((IManageExpression)parsedTree).SetParent( this.expressionTree );
743 ················}
744 ············}
745
746 ············CreateQueryContextsForTypes();
747 ········}
748
749 ········IServiceProvider ServiceProvider
750 ········{
751 ············get { return this.pm.ServiceProvider; }
752 ········}
753
754 ········/// <summary>
755 ········/// Gets the query parameters
756 ········/// </summary>
757 ········public ICollection<object> Parameters
758 ········{
759 ············get { return this.parameters; }
760 ········}
761
762 ········/// <summary>
763 ········/// Indicates whether subclasses are allowed in the query
764 ········/// </summary>
765 ········public bool AllowSubclasses
766 ········{
767 ············get { return this.allowSubclasses; }
768 ············set { this.allowSubclasses = value; }
769 ········}
770
771 ········/// <summary>
772 ········/// Gets or sets the relations to be queried in the query
773 ········/// </summary>
774 ········public IEnumerable<string> Prefetches
775 ········{
776 ············get { return this.prefetches; }
777 ············set { this.prefetches = value.ToList(); }
778 ········}
779
780 ········/// <summary>
781 ········/// Gets or sets orderings
782 ········/// </summary>
783 ········public List<QueryOrder> Orderings
784 ········{
785 ············get { return this.orderings; }
786 ············set { this.orderings = value.ToList(); }
787 ········}
788
789 ········/// <summary>
790 ········/// Gets or sets the amount of elements to be skipped in an ordered query
791 ········/// </summary>
792 ········/// <remarks>This is for paging support.</remarks>
793 ········public int Skip
794 ········{
795 ············get { return this.skip; }
796 ············set { this.skip = value; }
797 ········}
798
799 ········/// <summary>
800 ········/// Gets or sets the amount of elements to be taken in an ordered query
801 ········/// </summary>
802 ········/// <remarks>This is for paging support.</remarks>
803 ········public int Take
804 ········{
805 ············get { return this.take; }
806 ············set { this.take = value; }
807 ········}
808
809 ········/// <summary>
810 ········/// Adds a prefetch to the query
811 ········/// </summary>
812 ········/// <param name="s"></param>
813 ········[Obsolete("Prefetches are not yet implemented, but will be in future.")]
814 ········public void AddPrefetch( string s )
815 ········{
816 ············this.prefetches.Add( s );
817 ········}
818
819 ········/// <summary>
820 ········/// Removes a prefetch from the query
821 ········/// </summary>
822 ········/// <param name="s"></param>
823 ········public void RemovePrefetch( string s )
824 ········{
825 ············if (this.prefetches.Contains( s ))
826 ················this.prefetches.Remove( s );
827 ········}
828
829 #region IQuery Interface
830
831 ········System.Collections.IList IQuery.Execute()
832 ········{
833 ············return this.Execute();
834 ········}
835
836 ········IPersistenceCapable IQuery.ExecuteSingle()
837 ········{
838 ············return (IPersistenceCapable)this.ExecuteSingle( false );
839 ········}
840
841 ········IPersistenceCapable IQuery.ExecuteSingle( bool throwIfResultCountIsWrong )
842 ········{
843 ············return (IPersistenceCapable)this.ExecuteSingle( throwIfResultCountIsWrong );
844 ········}
845
846 ········ICollection<object> IQuery.Parameters => this.parameters;
847 ········ICollection<QueryOrder> IQuery.Orderings => this.orderings;
848 ········object IQuery.ExecuteAggregate( string field, AggregateType aggregateType ) => ExecuteAggregate( field, aggregateType );
849 ········bool IQuery.AllowSubclasses { get => this.allowSubclasses; set => this.allowSubclasses = value; }
850 ········int IQuery.Skip { get => this.skip; set => this.skip = value; }
851 ········int IQuery.Take { get => this.take; set => this.take = value; }
852 ········string IQuery.GeneratedQuery { get { return this.GeneratedQuery; } }
853
854 #endregion
855
856 ····}
857 }
858