Datei: NDODLL/PersistenceManager.cs

Last Commit (9daec7b)
1 //
2 // Copyright (c) 2002-2024 Mirko Matytschak
3 // (www.netdataobjects.de)
4 //
5 // Author: Mirko Matytschak
6 //
7 // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
8 // documentation files (the "Software"), to deal in the Software without restriction, including without limitation
9 // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
10 // Software, and to permit persons to whom the Software is furnished to do so, subject to the following
11 // conditions:
12
13 // The above copyright notice and this permission notice shall be included in all copies or substantial portions
14 // of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
17 // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
19 // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 // DEALINGS IN THE SOFTWARE.
21
22
23 using System;
24 using System.Text;
25 using System.IO;
26 using System.Collections;
27 using System.Collections.Generic;
28 using System.Data;
29 using System.Diagnostics;
30 using System.Reflection;
31 using System.Text.RegularExpressions;
32 using System.Linq;
33 using System.Xml.Linq;
34 using System.Data.Common;
35 using System.Runtime.CompilerServices;
36 using System.Threading;
37 using System.Threading.Tasks;
38
39 using NDO.Mapping;
40 using NDOInterfaces;
41 using NDO.ShortId;
42 using System.Globalization;
43 using NDO.Linq;
44 using NDO.Query;
45 using NDO.ChangeLogging;
46 using Microsoft.Extensions.DependencyInjection;
47 using Microsoft.Extensions.Logging;
48
49 namespace NDO
50 {
51 ····/// <summary>
52 ····/// Delegate type of an handler, which can be registered by the CollisionEvent of the PersistenceManager.
53 ····/// <see cref="NDO.PersistenceManager.CollisionEvent"/>
54 ····/// </summary>
55 ····public delegate void CollisionHandler(object o);
56 ····/// <summary>
57 ····/// Delegate type of an handler, which can be registered by the IdGenerationEvent event of the PersistenceManager.
58 ····/// <see cref="NDO.PersistenceManagerBase.IdGenerationEvent"/>
59 ····/// </summary>
60 ····public delegate void IdGenerationHandler(Type t, ObjectId oid);
61 ····/// <summary>
62 ····/// Delegate type of an handler, which can be registered by the OnSaving event of the PersistenceManager.
63 ····/// </summary>
64 ····public delegate void OnSavingHandler(ICollection l);
65 ····/// <summary>
66 ····/// Delegate type for the OnSavedEvent.
67 ····/// </summary>
68 ····/// <param name="auditSet"></param>
69 ····public delegate void OnSavedHandler(AuditSet auditSet);
70
71 ····/// <summary>
72 ····/// Delegate type of an handler, which can be registered by the ObjectNotPresentEvent of the PersistenceManager. The event will be called, if LoadData doesn't find an object with the given oid.
73 ····/// </summary>
74 ····/// <param name="pc"></param>
75 ····/// <returns>A boolean value which determines, if the handler could solve the situation.</returns>
76 ····/// <remarks>If the handler returns false, NDO will throw an exception.</remarks>
77 ····public delegate bool ObjectNotPresentHandler( IPersistenceCapable pc );
78
79 ····/// <summary>
80 ····/// Standard implementation of the IPersistenceManager interface. Provides transaction like manipulation of data sets.
81 ····/// This is the main class you'll work with in your application code. For more information see the topic "Persistence Manager" in the NDO Documentation.
82 ····/// </summary>
83 ····public class PersistenceManager : PersistenceManagerBase, IPersistenceManager
84 ····{········
85 ········private bool hollowMode = false;
86 ········private Dictionary<Relation, IMappingTableHandler> mappingHandler = new Dictionary<Relation,IMappingTableHandler>(); // currently used handlers
87
88 ········private Hashtable currentRelations = new Hashtable(); // Contains names of current bidirectional relations
89 ········private ObjectLock removeLock = new ObjectLock();
90 ········private ObjectLock addLock = new ObjectLock();
91 ········private ArrayList createdDirectObjects = new ArrayList(); // List of newly created objects that need to be stored twice to update foreign keys.
92 ········// List of created objects that use mapping table and need to be stored in mapping table
93 ········// after they have been stored to the database to update foreign keys.
94 ········private ArrayList createdMappingTableObjects = new ArrayList();··
95 ········private TypeManager typeManager;
96 ········internal bool DeferredMode { get; private set; }
97 ········private INDOTransactionScope transactionScope;
98 ········internal INDOTransactionScope TransactionScope => transactionScope ?? (transactionScope = ServiceProvider.GetRequiredService<INDOTransactionScope>().Initialize(this));········
99
100 ········private OpenConnectionListener openConnectionListener;
101
102 ········/// <summary>
103 ········/// Register a listener to this event if you work in concurrent scenarios and you use TimeStamps.
104 ········/// If a collision occurs, this event gets fired and gives the opportunity to handle the situation.
105 ········/// </summary>
106 ········public event CollisionHandler CollisionEvent;
107
108 ········/// <summary>
109 ········/// Register a listener to this event to handle situations where LoadData doesn't find an object.
110 ········/// The listener can determine, whether an exception should be thrown, if the situation occurs.
111 ········/// </summary>
112 ········public event ObjectNotPresentHandler ObjectNotPresentEvent;
113
114 ········/// <summary>
115 ········/// Register a listener to this event, if you want to be notified about the end
116 ········/// of a transaction. The listener gets a ICollection of all objects, which have been changed
117 ········/// during the transaction and are to be saved or deleted.
118 ········/// </summary>
119 ········public event OnSavingHandler OnSavingEvent;
120 ········/// <summary>
121 ········/// This event is fired at the very end of the Save() method. It provides lists of the added, changed, and deleted objects.
122 ········/// </summary>
123 ········public event OnSavedHandler OnSavedEvent;
124 ········
125 ········private const string hollowMarker = "Hollow";
126 ········private byte[] encryptionKey;
127 ········private List<RelationChangeRecord> relationChanges = new List<RelationChangeRecord>();
128 ········private bool isClosing = false;
129
130 ········/// <summary>
131 ········/// Gets a list of structures which represent relation changes, i.e. additions and removals
132 ········/// </summary>
133 ········protected internal List<RelationChangeRecord> RelationChanges
134 ········{
135 ············get { return this.relationChanges; }
136 ········}
137
138 ········/// <summary>
139 ········/// Initializes a new PersistenceManager instance.
140 ········/// </summary>
141 ········/// <param name="mappingFileName"></param>
142 ········protected override void Init(string mappingFileName)
143 ········{
144 ············try
145 ············{
146 ················base.Init(mappingFileName);
147 ············}
148 ············catch (Exception ex)
149 ············{
150 ················if (ex is NDOException)
151 ····················throw;
152 ················throw new NDOException(30, "Persistence manager initialization error: " + ex.ToString());
153 ············}
154
155 ········}
156
157 ········/// <summary>
158 ········/// Initializes the persistence manager
159 ········/// </summary>
160 ········/// <remarks>
161 ········/// Note: This is the method, which will be called from all different ways to instantiate a PersistenceManagerBase.
162 ········/// </remarks>
163 ········/// <param name="mapping"></param>
164 ········internal override void Init( Mappings mapping )
165 ········{
166 ············base.Init( mapping );
167
168 ············string dir = Path.GetDirectoryName( mapping.FileName );
169
170 ············string typesFile = Path.Combine( dir, "NDOTypes.xml" );
171 ············typeManager = new TypeManager( typesFile, this.mappings );
172
173 ············sm = new StateManager( this );
174
175 ············InitClasses();
176 ········}
177
178
179 ········/// <summary>
180 ········/// Standard Constructor.
181 ········/// </summary>
182 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
183 ········/// <remarks>
184 ········/// Searches for a mapping file in the application directory.
185 ········/// The constructor tries to find a file with the same name as
186 ········/// the assembly, but with the extension .ndo.xml. If the file is not found the constructor tries to find a
187 ········/// file called AssemblyName.ndo.mapping in the application directory.
188 ········/// </remarks>
189 ········public PersistenceManager( IServiceProvider scopedServiceProvider = null ) : base( scopedServiceProvider )
190 ········{
191 ········}
192
193 ········/// <summary>
194 ········/// Loads the mapping file from the specified location. This allows to use
195 ········/// different mapping files with different classes mapped in it.
196 ········/// </summary>
197 ········/// <param name="mappingFile">Path to the mapping file.</param>
198 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
199 ········/// <remarks>Only the Professional and Enterprise
200 ········/// Editions can handle more than one mapping file.</remarks>
201 ········public PersistenceManager(string mappingFile, IServiceProvider scopedServiceProvider = null) : base (mappingFile, scopedServiceProvider)
202 ········{
203 ········}
204
205 ········/// <summary>
206 ········/// Constructs a PersistenceManager and reuses a cached NDOMapping.
207 ········/// </summary>
208 ········/// <param name="mapping">The cached mapping object</param>
209 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
210 ········public PersistenceManager(NDOMapping mapping, IServiceProvider scopedServiceProvider = null) : base (mapping, scopedServiceProvider)
211 ········{
212 ········}
213
214 ········#region Object Container Stuff
215 ········/// <summary>
216 ········/// Gets a container of all loaded objects and tries to load all child objects,
217 ········/// which are reachable through composite relations.
218 ········/// </summary>
219 ········/// <returns>An ObjectContainer object.</returns>
220 ········/// <remarks>
221 ········/// It is not recommended, to transfer objects with a state other than Hollow,
222 ········/// Persistent, or Transient.
223 ········/// The transfer format is binary.
224 ········/// </remarks>
225 ········public ObjectContainer GetObjectContainer()
226 ········{
227 ············IList l = this.cache.AllObjects;
228 ············foreach(IPersistenceCapable pc in l)
229 ············{
230 ················if (pc.NDOObjectState == NDOObjectState.PersistentDirty)
231 ················{
232 ····················if (Logger != null)
233 ························Logger.LogWarning( "Call to GetObjectContainer returns changed objects." );
234 ················}
235 ············}
236
237 ············ObjectContainer oc = new ObjectContainer();
238 ············oc.AddList(l);
239 ············return oc;
240 ········}
241
242 ········/// <summary>
243 ········/// Returns a container of all objects provided in the objects list and searches for
244 ········/// child objects according to the serFlags.
245 ········/// </summary>
246 ········/// <param name="objects">The list of the root objects to add to the container.</param>
247 ········/// <returns>An ObjectContainer object.</returns>
248 ········/// <remarks>
249 ········/// It is not recommended, to transfer objects with a state other than Hollow,
250 ········/// Persistent, or Transient.
251 ········/// </remarks>
252 ········public ObjectContainer GetObjectContainer(IList objects)
253 ········{
254 ············foreach(object o in objects)
255 ············{
256 ················CheckPc(o);
257 ················IPersistenceCapable pc = o as IPersistenceCapable;
258 ················if (pc.NDOObjectState == NDOObjectState.Hollow)
259 ····················LoadData(pc);
260 ············}
261 ············ObjectContainer oc = new ObjectContainer();
262 ············oc.AddList(objects);
263 ············return oc;
264 ········}
265
266
267 ········/// <summary>
268 ········/// Returns a container containing the provided object
269 ········/// and tries to load all child objects
270 ········/// reachable through composite relations.
271 ········/// </summary>
272 ········/// <param name="obj">The object to be added to the container.</param>
273 ········/// <returns>An ObjectContainer object.</returns>
274 ········/// <remarks>
275 ········/// It is not recommended, to transfer objects with a state other than Hollow,
276 ········/// Persistent, or Transient.
277 ········/// The transfer format is binary.
278 ········/// </remarks>
279 ········public ObjectContainer GetObjectContainer(Object obj)
280 ········{
281 ············CheckPc(obj);
282 ············if (((IPersistenceCapable)obj).NDOObjectState == NDOObjectState.Hollow)
283 ················LoadData(obj);
284 ············ObjectContainer oc = new ObjectContainer();
285 ············oc.AddObject(obj);
286 ············return oc;
287 ········}
288
289 ········/// <summary>
290 ········/// Merges an object container to the active objects in the pm. All changes and the state
291 ········/// of the objects will be taken over by the pm.
292 ········/// </summary>
293 ········/// <remarks>
294 ········/// The parameter can be either an ObjectContainer or a ChangeSetContainer.
295 ········/// The flag MarkAsTransient can be used to perform a kind
296 ········/// of object based replication using the ObjectContainer class.
297 ········/// Objects, which are persistent at one machine, can be transfered
298 ········/// to a second machine and treated by the receiving PersistenceManager like a newly created
299 ········/// object. The receiving PersistenceManager will use MakePersistent to store the whole
300 ········/// transient object tree.
301 ········/// There is one difference to freshly created objects: If an object id exists, it will be
302 ········/// serialized. If the NDOOidType-Attribute is valid for the given class, the transfered
303 ········/// oids will be reused by the receiving PersistenceManager.
304 ········/// </remarks>
305 ········/// <param name="ocb">The object container to be merged.</param>
306 ········public void MergeObjectContainer(ObjectContainerBase ocb)
307 ········{
308 ············ChangeSetContainer csc = ocb as ChangeSetContainer;
309 ············if (csc != null)
310 ············{
311 ················MergeChangeSet(csc);
312 ················return;
313 ············}
314 ············ObjectContainer oc = ocb as ObjectContainer;
315 ············if (oc != null)
316 ············{
317 ················InternalMergeObjectContainer(oc);
318 ················return;
319 ············}
320 ············throw new NDOException(42, "Wrong argument type: MergeObjectContainer expects either an ObjectContainer or a ChangeSetContainer object as parameter.");
321 ········}
322
323
324 ········void InternalMergeObjectContainer(ObjectContainer oc)
325 ········{
326 ············// TODO: Check, if other states are useful. Find use scenarios.
327 ············foreach(IPersistenceCapable pc in oc.RootObjects)
328 ············{
329 ················if (pc.NDOObjectState == NDOObjectState.Transient)
330 ····················MakePersistent(pc);
331 ············}
332 ············foreach(IPersistenceCapable pc in oc.RootObjects)
333 ············{
334 ················new OnlineMergeIterator(this.sm, this.cache).Iterate(pc);
335 ············}
336 ········}
337
338 ········void MergeChangeSet(ChangeSetContainer cs)
339 ········{
340 ············foreach(IPersistenceCapable pc in cs.AddedObjects)
341 ············{
342 ················InternalMakePersistent(pc, false);
343 ············}
344 ············foreach(ObjectId oid in cs.DeletedObjects)
345 ············{
346 ················IPersistenceCapable pc2 = FindObject(oid);
347 ················Delete(pc2);
348 ············}
349 ············foreach(IPersistenceCapable pc in cs.ChangedObjects)
350 ············{
351 ················IPersistenceCapable pc2 = FindObject(pc.NDOObjectId);
352 ················Class pcClass = GetClass(pc);
353 ················// Make sure, the object is loaded.
354 ················if (pc2.NDOObjectState == NDOObjectState.Hollow)
355 ····················LoadData(pc2);
356 ················MarkDirty( pc2 );··// This locks the object and generates a LockEntry, which contains a row
357 ················var entry = cache.LockedObjects.FirstOrDefault( e => e.pc.NDOObjectId == pc.NDOObjectId );
358 ················DataRow row = entry.row;
359 ················pc.NDOWrite(row, pcClass.ColumnNames, 0);
360 ················pc2.NDORead(row, pcClass.ColumnNames, 0);
361 ············}
362 ············foreach(RelationChangeRecord rcr in cs.RelationChanges)
363 ············{
364 ················IPersistenceCapable parent = FindObject(rcr.Parent.NDOObjectId);
365 ················IPersistenceCapable child = FindObject(rcr.Child.NDOObjectId);
366 ················Class pcClass = GetClass(parent);
367 ················Relation r = pcClass.FindRelation(rcr.RelationName);
368 ················if (!parent.NDOLoadState.RelationLoadState[r.Ordinal])
369 ····················LoadRelation(parent, r, true);
370 ················if (rcr.IsAdded)
371 ················{
372 ····················InternalAddRelatedObject(parent, r, child, true);
373 ····················if (r.Multiplicity == RelationMultiplicity.Element)
374 ····················{
375 ························mappings.SetRelationField(parent, r.FieldName, child);
376 ····················}
377 ····················else
378 ····················{
379 ························IList l = mappings.GetRelationContainer(parent, r);
380 ························l.Add(child);
381 ····················}
382 ················}
383 ················else
384 ················{
385 ····················RemoveRelatedObject(parent, r.FieldName, child);
386 ····················if (r.Multiplicity == RelationMultiplicity.Element)
387 ····················{
388 ························mappings.SetRelationField(parent, r.FieldName, null);
389 ····················}
390 ····················else
391 ····················{
392 ························IList l = mappings.GetRelationContainer(parent, r);
393 ························try
394 ························{
395 ····························ObjectListManipulator.Remove(l, child);
396 ························}
397 ························catch
398 ························{
399 ····························throw new NDOException(50, "Error while merging a ChangeSetContainer: Child " + child.NDOObjectId.ToString() + " doesn't exist in relation " + parent.GetType().FullName + '.' + r.FieldName);
400 ························}
401 ····················}
402 ················}
403 ············}
404
405 ········}
406 ········#endregion
407
408 ········#region Implementation of IPersistenceManager
409
410 ········// Complete documentation can be found in IPersistenceManager
411
412
413 ········void WriteDependentForeignKeysToRow(IPersistenceCapable pc, Class cl, DataRow row)
414 ········{
415 ············if (!cl.Oid.IsDependent)
416 ················return;
417 ············WriteForeignKeysToRow(pc, row);
418 ········}
419
420 ········void InternalMakePersistent(IPersistenceCapable pc, bool checkRelations)
421 ········{
422 ············// Object is now under control of the state manager
423 ············pc.NDOStateManager = sm;
424
425 ············Type pcType = pc.GetType();
426 ············Class pcClass = GetClass(pc);
427
428 ············// Create new object
429 ············DataTable dt = GetTable(pcType);
430 ············DataRow row = dt.NewRow();·· // In case of autoincremented oid, the row has a temporary oid value
431
432 ············// In case of a Guid oid the value will be computed now.
433 ············foreach (OidColumn oidColumn in pcClass.Oid.OidColumns)
434 ············{
435 ················if (oidColumn.SystemType == typeof(Guid) && oidColumn.FieldName == null && oidColumn.RelationName ==null)
436 ················{
437 ····················if (dt.Columns[oidColumn.Name].DataType == typeof(string))
438 ························row[oidColumn.Name] = Guid.NewGuid().ToString();
439 ····················else
440 ························row[oidColumn.Name] = Guid.NewGuid();
441 ················}
442 ············}
443
444 ············WriteObject(pc, row, pcClass.ColumnNames, 0); // save current state in DS
445
446 ············// If the object is merged from an ObjectContainer, the id should be reused,
447 ············// if the id is client generated (not Autoincremented).
448 ············// In every other case, the oid is set to null, to force generating a new oid.
449 ············bool fireIdGeneration = (Object)pc.NDOObjectId == null;
450 ············if ((object)pc.NDOObjectId != null)
451 ············{
452 ················bool hasAutoincrement = false;
453 ················foreach (OidColumn oidColumn in pcClass.Oid.OidColumns)
454 ················{
455 ····················if (oidColumn.AutoIncremented)
456 ····················{
457 ························hasAutoincrement = true;
458 ························break;
459 ····················}
460 ················}
461 ················if (hasAutoincrement) // can't store existing id
462 ················{
463 ····················pc.NDOObjectId = null;
464 ····················fireIdGeneration = true;
465 ················}
466 ············}
467
468 ············// In case of a dependent class the oid has to be read from the fields according to the relations
469 ············WriteDependentForeignKeysToRow(pc, pcClass, row);
470
471 ············if ((object)pc.NDOObjectId == null)
472 ············{
473 ················pc.NDOObjectId = ObjectIdFactory.NewObjectId(pcType, pcClass, row, this.typeManager);
474 ············}
475
476 ············if (!pcClass.Oid.IsDependent) // Dependent keys can't be filled with user defined data
477 ············{
478 ················if (fireIdGeneration)
479 ····················FireIdGenerationEvent(pcType, pc.NDOObjectId);
480 ················// At this place the oid might have been
481 ················// - deserialized (MergeObjectContainer)
482 ················// - created using NewObjectId
483 ················// - defined by the IdGenerationEvent
484
485 ················// At this point we have a valid oid.
486 ················// If the object has a field mapped to the oid we have
487 ················// to write back the oid to the field
488 ················int i = 0;
489 ················new OidColumnIterator(pcClass).Iterate(delegate(OidColumn oidColumn, bool isLastElement)
490 ················{
491 ····················if (oidColumn.FieldName != null)
492 ····················{
493 ························FieldInfo fi = new BaseClassReflector(pcType).GetField(oidColumn.FieldName, BindingFlags.NonPublic | BindingFlags.Instance);
494 ························fi.SetValue(pc, pc.NDOObjectId.Id[i]);
495 ····················}
496 ····················i++;
497 ················});
498
499
500
501 ················// Now write back the data into the row
502 ················pc.NDOObjectId.Id.ToRow(pcClass, row);
503 ············}
504
505 ············
506 ············ReadLostForeignKeysFromRow(pcClass, pc, row);··// they contain all DBNull at the moment
507 ············dt.Rows.Add(row);
508
509 ············cache.Register(pc);
510
511 ············// new object that has never been written to the DS
512 ············pc.NDOObjectState = NDOObjectState.Created;
513 ············// Mark all Relations as loaded
514 ············SetRelationState(pc);
515
516 ············if (checkRelations)
517 ············{
518 ················// Handle related objects:
519 ················foreach(Relation r in pcClass.Relations)
520 ················{
521 ····················if (r.Multiplicity == RelationMultiplicity.Element)
522 ····················{
523 ························IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
524 ························if(child != null)
525 ························{
526 ····························AddRelatedObject(pc, r, child);
527 ························}
528 ····················}
529 ····················else
530 ····················{
531 ························IList list = mappings.GetRelationContainer(pc, r);
532 ························if(list != null)
533 ························{
534 ····························foreach(IPersistenceCapable relObj in list)
535 ····························{
536 ································if (relObj != null)
537 ····································AddRelatedObject(pc, r, relObj);
538 ····························}
539 ························}
540 ····················}
541 ················}
542 ············}
543
544 ············var relations··= CollectRelationStates(pc);
545 ············cache.Lock(pc, row, relations);
546 ········}
547
548
549 ········/// <summary>
550 ········/// Make an object persistent.
551 ········/// </summary>
552 ········/// <param name="o">the transient object that should be made persistent</param>
553 ········public void MakePersistent(object o)
554 ········{
555 ············if (IsClosed)
556 ················throw new ObjectDisposedException( GetType().Name );····
557
558 ············IPersistenceCapable pc = CheckPc(o);
559
560 ············//Debug.WriteLine("MakePersistent: " + pc.GetType().Name);
561 ············//Debug.Indent();
562
563 ············if (pc.NDOObjectState != NDOObjectState.Transient)
564 ················throw new NDOException(54, "MakePersistent: Object is already persistent: " + pc.NDOObjectId.Dump());
565
566 ············InternalMakePersistent(pc, true);
567
568 ········}
569
570
571
572 ········//········/// <summary>
573 ········//········/// Checks, if an object has a valid id, which was created by the database
574 ········//········/// </summary>
575 ········//········/// <param name="pc"></param>
576 ········//········/// <returns></returns>
577 ········//········private bool HasValidId(IPersistenceCapable pc)
578 ········//········{
579 ········//············if (this.IdGenerationEvent != null)
580 ········//················return true;
581 ········//············return (pc.NDOObjectState != NDOObjectState.Created && pc.NDOObjectState != NDOObjectState.Transient);
582 ········//········}
583
584
585 ········private void CreateAddedObjectRow(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj, bool makeRelObjPersistent)
586 ········{
587 ············// for a "1:n"-Relation w/o mapping table, we add the foreign key here.
588 ············if(r.HasSubclasses)
589 ············{
590 ················// we don't support 1:n with foreign fields in subclasses because we would have to
591 ················// search for objects in all subclasses! Instead use a mapping table.
592 ················// throw new NDOException(55, "1:n Relations with subclasses must use a mapping table: " + r.FieldName);
593 ················Debug.WriteLine("CreateAddedObjectRow: Polymorphic 1:n-relation " + r.Parent.FullName + "." + r.FieldName + " w/o mapping table");
594 ············}
595
596 ············if (!makeRelObjPersistent)
597 ················MarkDirty(relObj);
598 ············// Because we just marked the object as dirty, we know it's in the cache, so we don't supply the idColumn
599 ············DataRow relObjRow = this.cache.GetDataRow(relObj);
600
601 ············if (relObjRow == null)
602 ················throw new InternalException(537, "CreateAddedObjectRow: relObjRow == null");
603
604 ············pc.NDOObjectId.Id.ToForeignKey(r, relObjRow);
605
606 ············if (relObj.NDOLoadState.LostRowInfo == null)
607 ············{
608 ················ReadLostForeignKeysFromRow(GetClass(relObj), relObj, relObjRow);
609 ············}
610 ············else
611 ············{
612 ················relObj.NDOLoadState.ReplaceRowInfos(r, pc.NDOObjectId.Id);
613 ············}
614 ········}
615
616 ········private void PatchForeignRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
617 ········{
618 ············switch(relObj.NDOObjectState)
619 ············{
620 ················case NDOObjectState.Persistent:
621 ····················MarkDirty(relObj);
622 ····················break;
623 ················case NDOObjectState.Hollow:
624 ····················LoadData(relObj);
625 ····················MarkDirty(relObj);
626 ····················break;
627 ············}
628
629 ············if(r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
630 ············{
631 ················IPersistenceCapable newpc;
632 ················if((newpc = (IPersistenceCapable) mappings.GetRelationField(relObj, r.ForeignRelation.FieldName)) != null)
633 ················{
634 ····················if (newpc != pc)
635 ························throw new NDOException(56, "Object is already part of another relation: " + relObj.NDOObjectId.Dump());
636 ················}
637 ················else
638 ················{
639 ····················mappings.SetRelationField(relObj, r.ForeignRelation.FieldName, pc);
640 ················}
641 ············}
642 ············else
643 ············{
644 ················if (!relObj.NDOGetLoadState(r.ForeignRelation.Ordinal))
645 ····················LoadRelation(relObj, r.ForeignRelation, true);
646 ················IList l = mappings.GetRelationContainer(relObj, r.ForeignRelation);
647 ················if(l == null)
648 ················{
649 ····················try
650 ····················{
651 ························l = mappings.CreateRelationContainer(relObj, r.ForeignRelation);
652 ····················}
653 ····················catch
654 ····················{
655 ························throw new NDOException(57, "Can't construct IList member " + relObj.GetType().FullName + "." + r.FieldName + ". Initialize the field in the default class constructor.");
656 ····················}
657 ····················mappings.SetRelationContainer(relObj, r.ForeignRelation, l);
658 ················}
659 ················// Hack: Es sollte erst gar nicht zu diesem Aufruf kommen.
660 ················// Zus�tzlicher Funktions-Parameter addObjectToList oder so.
661 ················if (!ObjectListManipulator.Contains(l, pc))
662 ····················l.Add(pc);
663 ············}
664 ············//AddRelatedObject(relObj, r.ForeignRelation, pc);
665 ········}
666
667
668 ········/// <summary>
669 ········/// Add a related object to the specified object.
670 ········/// </summary>
671 ········/// <param name="pc">the parent object</param>
672 ········/// <param name="fieldName">the field name of the relation</param>
673 ········/// <param name="relObj">the related object that should be added</param>
674 ········internal virtual void AddRelatedObject(IPersistenceCapable pc, string fieldName, IPersistenceCapable relObj)
675 ········{
676 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient);
677 ············Relation r = mappings.FindRelation(pc, fieldName);
678 ············AddRelatedObject(pc, r, relObj);
679 ········}
680
681 ········/// <summary>
682 ········/// Core functionality to add an object to a relation container or relation field.
683 ········/// </summary>
684 ········/// <param name="pc"></param>
685 ········/// <param name="r"></param>
686 ········/// <param name="relObj"></param>
687 ········/// <param name="isMerging"></param>
688 ········protected virtual void InternalAddRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj, bool isMerging)
689 ········{
690 ············
691 ············// avoid recursion
692 ············if (!addLock.GetLock(relObj))
693 ················return;
694
695 ············try
696 ············{
697 ················//TODO: We need a relation management, which is independent of
698 ················//the state management of an object. Currently the relation
699 ················//lists or elements are cached for restore, if an object is marked dirty.
700 ················//Thus we have to mark dirty our parent object in any case at the moment.
701 ················MarkDirty(pc);
702
703 ················//We should mark pc as dirty if we have a 1:1 w/o mapping table
704 ················//We should mark relObj as dirty if we have a 1:n w/o mapping table
705 ················//The latter happens in CreateAddedObjectRow
706
707 ················Class relClass = GetClass(relObj);
708
709 ················if (r.Multiplicity == RelationMultiplicity.Element
710 ····················&& r.HasSubclasses
711 ····················&& r.MappingTable == null················
712 ····················&& !this.HasOwnerCreatedIds
713 ····················&& GetClass(pc).Oid.HasAutoincrementedColumn
714 ····················&& !relClass.HasGuidOid)
715 ················{
716 ····················if (pc.NDOObjectState == NDOObjectState.Created && (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient ))
717 ························throw new NDOException(61, "Can't assign object of type " + relObj + " to relation " + pc.GetType().FullName + "." + r.FieldName + ". The parent object must be saved first to obtain the Id (for example with pm.Save(true)). As an alternative you can use client generated Id's or a mapping table.");
718 ····················if (r.Composition)
719 ························throw new NDOException(62, "Can't assign object of type " + relObj + " to relation " + pc.GetType().FullName + "." + r.FieldName + ". Can't handle a polymorphic composite relation with cardinality 1 with autonumbered id's. Use a mapping table or client generated id's.");
720 ····················if (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient)
721 ························throw new NDOException(63, "Can't assign an object of type " + relObj + " to relation " + pc.GetType().FullName + "." + r.FieldName + ". The child object must be saved first to obtain the Id (for example with pm.Save(true)). As an alternative you can use client generated Id's or a mapping table." );
722 ················}
723
724 ················bool isDependent = relClass.Oid.IsDependent;
725
726 ················if (r.Multiplicity == RelationMultiplicity.Element && isDependent)
727 ····················throw new NDOException(28, "Relations to intermediate classes must have RelationMultiplicity.List.");
728
729 ················// Need to patch pc into the relation relObj->pc, because
730 ················// the oid is built on base of this information
731 ················if (isDependent)
732 ················{
733 ····················CheckDependentKeyPreconditions(pc, r, relObj, relClass);
734 ················}
735
736 ················if (r.Composition || isDependent)
737 ················{
738 ····················if (!isMerging || relObj.NDOObjectState == NDOObjectState.Transient)
739 ························MakePersistent(relObj);
740 ················}
741
742 ················if(r.MappingTable == null)
743 ················{
744 ····················if (r.Bidirectional)
745 ····················{
746 ························// This object hasn't been saved yet, so the key is wrong.
747 ························// Therefore, the child must be written twice to update the foreign key.
748 #if trace
749 ························System.Text.StringBuilder sb = new System.Text.StringBuilder();
750 ························if (r.Multiplicity == RelationMultiplicity.Element)
751 ····························sb.Append("1");
752 ························else
753 ····························sb.Append("n");
754 ························sb.Append(":");
755 ························if (r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
756 ····························sb.Append("1");
757 ························else
758 ····························sb.Append("n");
759 ························sb.Append ("OwnCreatedOther");
760 ························sb.Append(relObj.NDOObjectState.ToString());
761 ························sb.Append(' ');
762
763 ························sb.Append(types[0].ToString());
764 ························sb.Append(' ');
765 ························sb.Append(types[1].ToString());
766 ························Debug.WriteLine(sb.ToString());
767 #endif
768 ························//························if (r.Multiplicity == RelationMultiplicity.Element
769 ························//····························&& r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
770 ························//························{
771 ························// Element means:
772 ························// pc is keyholder
773 ························// -> relObj is saved first
774 ························// -> UpdateOrder(pc) > UpdateOrder(relObj)
775 ························// Both are Created - use type sort order
776 ························if (pc.NDOObjectState == NDOObjectState.Created && (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient)
777 ····························&& GetClass(pc).Oid.HasAutoincrementedColumn && GetClass(relObj).Oid.HasAutoincrementedColumn)
778 ························{
779 ····························if (mappings.GetUpdateOrder(pc.GetType())
780 ································< mappings.GetUpdateOrder(relObj.GetType()))
781 ································createdDirectObjects.Add(pc);
782 ····························else
783 ································createdDirectObjects.Add( relObj );
784 ························}
785 ····················}
786 ····················if (r.Multiplicity == RelationMultiplicity.List)
787 ····················{
788 ························CreateAddedObjectRow(pc, r, relObj, r.Composition);
789 ····················}
790 ················}
791 ················else
792 ················{
793 ····················createdMappingTableObjects.Add(new MappingTableEntry(pc, relObj, r));
794 ················}
795 ················if(r.Bidirectional)
796 ················{
797 ····················if (r.Multiplicity == RelationMultiplicity.List && mappings.GetRelationField(relObj, r.ForeignRelation.FieldName) == null)
798 ····················{
799 ························if ( r.ForeignRelation.Multiplicity == RelationMultiplicity.Element )
800 ····························mappings.SetRelationField(relObj, r.ForeignRelation.FieldName, pc);
801 ····················}
802 ····················else if ( !addLock.IsLocked( pc ) )
803 ····················{
804 ························PatchForeignRelation( pc, r, relObj );
805 ····················}
806 ················}
807
808 ················this.relationChanges.Add( new RelationChangeRecord( pc, relObj, r.FieldName, true ) );
809 ············}
810 ············finally
811 ············{
812 ················addLock.Unlock(relObj);
813 ················//Debug.Unindent();
814 ············}
815 ········}
816
817 ········/// <summary>
818 ········/// Returns an integer value which determines the rank of the given type in the update order list.
819 ········/// </summary>
820 ········/// <param name="t">The type to determine the update order.</param>
821 ········/// <returns>An integer value determining the rank of the given type in the update order list.</returns>
822 ········/// <remarks>
823 ········/// This method is used by NDO for diagnostic purposes. There is no value in using this method in user code.
824 ········/// </remarks>
825 ········public int GetUpdateRank(Type t)
826 ········{
827 ············return mappings.GetUpdateOrder(t);
828 ········}
829
830 ········/// <summary>
831 ········/// Add a related object to the specified object.
832 ········/// </summary>
833 ········/// <param name="pc">the parent object</param>
834 ········/// <param name="r">the relation mapping info</param>
835 ········/// <param name="relObj">the related object that should be added</param>
836 ········protected virtual void AddRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
837 ········{
838 ············//············string idstr;
839 ············//············if (relObj.NDOObjectId == null)
840 ············//················idstr = relObj.GetType().ToString();
841 ············//············else
842 ············//················idstr = relObj.NDOObjectId.Dump();
843 ············//Debug.WriteLine("AddRelatedObject " + pc.NDOObjectId.Dump() + " " + idstr);
844 ············//Debug.Indent();
845
846 ············Class relClass = GetClass(relObj);
847 ············bool isDependent = relClass.Oid.IsDependent;
848
849 ············// Do some checks to guarantee that the assignment is correct
850 ············if(r.Composition)
851 ············{
852 ················if(relObj.NDOObjectState != NDOObjectState.Transient)
853 ················{
854 ····················throw new NDOException(58, "Can only add transient objects in Composite relation " + pc.GetType().FullName + "->" + r.ReferencedTypeName + ".");
855 ················}
856 ············}
857 ············else
858 ············{
859 ················if(relObj.NDOObjectState == NDOObjectState.Transient && !isDependent)
860 ················{
861 ····················throw new NDOException(59, "Can only add persistent objects in Assoziation " + pc.GetType().FullName + "->" + r.ReferencedTypeName + ".");
862 ················}
863 ············}
864
865 ············if(!r.ReferencedType.IsAssignableFrom(relObj.GetType()))
866 ············{
867 ················throw new NDOException(60, "AddRelatedObject: Related object must be assignable to type: " + r.ReferencedTypeName + ". Assigned object was: " + relObj.NDOObjectId.Dump() + " Type = " + relObj.GetType());
868 ············}
869
870 ············InternalAddRelatedObject(pc, r, relObj, false);
871
872 ········}
873
874 ········private void CheckDependentKeyPreconditions(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj, Class relClass)
875 ········{
876 ············// Need to patch pc into the relation relObj->pc, because
877 ············// the oid is built on base of this information
878 ············// The second relation has to be set before adding relObj
879 ············// to the relation list.
880 ············PatchForeignRelation(pc, r, relObj);
881 ············IPersistenceCapable parent;
882 ············foreach (Relation oidRelation in relClass.Oid.Relations)
883 ············{
884 ················parent = (IPersistenceCapable)mappings.GetRelationField(relObj, oidRelation.FieldName);
885 ················if (parent == null)
886 ····················throw new NDOException(41, "'" + relClass.FullName + "." + oidRelation.FieldName + "': One of the defining relations of a dependent class object is null - have a look at the documentation about how to initialize dependent class objects.");
887 ················if (parent.NDOObjectState == NDOObjectState.Transient)
888 ····················throw new NDOException(59, "Can only add persistent objects in Assoziation " + relClass.FullName + "." + oidRelation.FieldName + ". Make the object of type " + parent.GetType().FullName + " persistent.");
889
890 ············}
891 ········}
892
893
894 ········/// <summary>
895 ········/// Remove a related object from the specified object.
896 ········/// </summary>
897 ········/// <param name="pc">the parent object</param>
898 ········/// <param name="fieldName">Field name of the relation</param>
899 ········/// <param name="relObj">the related object that should be removed</param>
900 ········internal virtual void RemoveRelatedObject(IPersistenceCapable pc, string fieldName, IPersistenceCapable relObj)
901 ········{
902 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient);
903 ············Relation r = mappings.FindRelation(pc, fieldName);
904 ············InternalRemoveRelatedObject(pc, r, relObj, true);
905 ········}
906
907 ········/// <summary>
908 ········/// Registers a listener which will be notified, if a new connection is opened.
909 ········/// </summary>
910 ········/// <param name="listener">Delegate of a listener function</param>
911 ········/// <remarks>The listener is called the first time a certain connection is used. A call to Save() resets the connection list so that the listener is called again.</remarks>
912 ········public virtual void RegisterConnectionListener(OpenConnectionListener listener)
913 ········{
914 ············this.openConnectionListener = listener;
915 ········}
916
917 ········internal string OnNewConnection(NDO.Mapping.Connection conn)
918 ········{
919 ············if (openConnectionListener != null)
920 ················return openConnectionListener(conn);
921 ············return conn.Name;
922 ········}
923
924
925 ········/*
926 ········doCommit should be:
927 ········
928 ····················Query····Save····Save(true)
929 ········Optimistic····1········1········0
930 ········Pessimistic····0········1········0
931 ············
932 ········Deferred Mode············
933 ····················Query····Save····Save(true)
934 ········Optimistic····0········1········0
935 ········Pessimistic····0········1········0
936 ········ */
937
938 ········internal void CheckEndTransaction(bool doCommit)
939 ········{
940 ············CheckEndTransactionAsync( doCommit ).ConfigureAwait( false ).GetAwaiter().GetResult();
941 ········}
942
943 ········internal async Task CheckEndTransactionAsync( bool doCommit, CancellationToken cancellationToken = default )
944 ········{
945 ············if (doCommit)
946 ············{
947 ················await TransactionScope.CompleteAsync( cancellationToken ).ConfigureAwait( false );
948 ············}
949 ········}
950
951 ········internal Task CheckTransactionAsync( IPersistenceHandlerBase handler, Type t, CancellationToken cancellationToken = default )
952 ········{
953 ············return CheckTransactionAsync( handler, this.GetClass( t ).Connection, cancellationToken );
954 ········}
955
956 ········int activeOperation;
957 ········readonly AsyncLocal<bool> ownsOperation = new AsyncLocal<bool>();
958
959 ········/// <summary>
960 ········/// Marks the begin of an operation with database access. Detects concurrent usage of the PersistenceManager.
961 ········/// </summary>
962 ········/// <param name="caller">The name of the calling method</param>
963 ········/// <returns>An object, which marks the end of the operation if disposed.</returns>
964 ········/// <remarks>
965 ········/// Nested calls in the same logical flow (e.g. lazy loading in an OnSaving handler) are allowed.
966 ········/// The AsyncLocal flows with the ExecutionContext into all awaited calls, but not back to the caller of an async method.
967 ········/// So two concurrently started tasks don't share the ownership.
968 ········/// </remarks>
969 ········internal OperationGuard EnterOperation( [CallerMemberName] string caller = null )
970 ········{
971 ············if (this.ownsOperation.Value)
972 ················return default;··// Nested call in the same logical flow
973 ············if (Interlocked.CompareExchange( ref this.activeOperation, 1, 0 ) != 0)
974 ················throw new NDOException( 122, $"{caller}: The PersistenceManager is already in use by another operation. A PersistenceManager must not be used concurrently. Await each call before starting the next one." );
975 ············this.ownsOperation.Value = true;
976 ············return new OperationGuard( this );
977 ········}
978
979 ········internal readonly struct OperationGuard : IDisposable
980 ········{
981 ············readonly PersistenceManager pm;
982
983 ············public OperationGuard( PersistenceManager pm )
984 ············{
985 ················this.pm = pm;
986 ············}
987
988 ············public void Dispose()
989 ············{
990 ················if (this.pm == null)
991 ····················return;··// Nested call: nothing to release
992 ················this.pm.ownsOperation.Value = false;
993 ················Volatile.Write( ref this.pm.activeOperation, 0 );
994 ············}
995 ········}
996
997 ········/// <summary>
998 ········/// Each and every database operation has to be preceded by a call to this function.
999 ········/// </summary>
1000 ········internal async Task CheckTransactionAsync( IPersistenceHandlerBase handler, Connection ndoConn, CancellationToken cancellationToken = default )
1001 ········{
1002 ············await TransactionScope.CheckTransactionAsync( cancellationToken ).ConfigureAwait( false );
1003 ············
1004 ············if (handler.Connection == null)
1005 ············{
1006 ················handler.Connection = await TransactionScope.GetConnectionAsync(ndoConn, () =>
1007 ················{
1008 ····················IProvider p = ndoConn.Parent.GetProvider( ndoConn );
1009 ····················string connStr = this.OnNewConnection( ndoConn );
1010 ····················var connection = p.NewConnection( connStr );
1011 ····················if (connection == null)
1012 ························throw new NDOException( 119, $"Can't construct connection for {connStr}. The provider returns null." );
1013 ····················LogIfVerbose( $"Creating a connection object for {ndoConn.DisplayName}" );
1014 ····················return connection;
1015 ················}, cancellationToken ).ConfigureAwait( false );
1016 ············}
1017
1018 ············if (TransactionMode != TransactionMode.None)
1019 ············{
1020 ················handler.Transaction = TransactionScope.GetTransaction( ndoConn.ID );
1021 ············}
1022
1023 ············// There are tests with a handler mock that always returns zero for the Connection property.
1024 ············if (handler.Connection != null && handler.Connection.State != ConnectionState.Open)
1025 ············{
1026 ················await handler.Connection.OpenAsync( cancellationToken ).ConfigureAwait( false );
1027 ················var serverId = ndoConn.Provider.GetConnectionId( handler.Connection );
1028 ················LogIfVerbose( $"Opening connection {serverId} = '{ndoConn.DisplayName}'" );
1029 ············}
1030 ········}
1031
1032 ········/// <summary>
1033 ········/// Event Handler for the ConcurrencyError event of the IPersistenceHandler.
1034 ········/// We try to tell the object which caused the concurrency exception, that a collicion occured.
1035 ········/// This is possible if there is a listener for the CollisionEvent.
1036 ········/// Else we throw an exception.
1037 ········/// </summary>
1038 ········/// <param name="ex">Concurrency Exception which was catched during update.</param>
1039 ········private void OnConcurrencyError(System.Data.DBConcurrencyException ex)
1040 ········{
1041 ············DataRow row = ex.Row;
1042 ············if (row == null || CollisionEvent == null || CollisionEvent.GetInvocationList().Length == 0)
1043 ················throw(ex);
1044 ············if (row.RowState == DataRowState.Detached)
1045 ················return;
1046 ············foreach (Cache.Entry e in cache.LockedObjects)
1047 ············{
1048 ················if (e.row == row)
1049 ················{
1050 ····················CollisionEvent(e.pc);
1051 ····················return;
1052 ················}
1053 ············}
1054 ············throw ex;
1055 ········}
1056
1057
1058 ········private void ReadObject(IPersistenceCapable pc, DataRow row, string[] fieldNames, int startIndex)
1059 ········{
1060 ············Class cl = GetClass(pc);
1061 ············string[] etypes = cl.EmbeddedTypes.ToArray();
1062 ············Dictionary<string,MemberInfo> persistentFields = null;
1063 ············if (etypes.Length > 0)
1064 ············{
1065 ················FieldMap fm = new FieldMap(cl);
1066 ················persistentFields = fm.PersistentFields;
1067 ············}
1068 ············foreach(string s in etypes)
1069 ············{
1070 ················try
1071 ················{
1072 ····················NDO.Mapping.Field f = cl.FindField(s);
1073 ····················if (f == null)
1074 ························continue;
1075 ····················object o = row[f.Column.Name];
1076 ····················string[] arr = s.Split('.');
1077 ····················// Suche Embedded Type-Feld mit Namen arr[0]
1078 ····················BaseClassReflector bcr = new BaseClassReflector(pc.GetType());
1079 ····················FieldInfo parentFi = bcr.GetField(arr[0], BindingFlags.NonPublic | BindingFlags.Instance);
1080 ····················// Hole das Embedded Object
1081 ····················object parentOb = parentFi.GetValue(pc);
1082
1083 ····················if (parentOb == null)
1084 ························throw new Exception(String.Format("Can't read subfield {0} of type {1}, because the field {2} is null. Initialize the field {2} in your default constructor.", s, pc.GetType().FullName, arr[0]));
1085
1086 ····················// Suche darin das Feld mit Namen Arr[1]
1087
1088 ····················FieldInfo childFi = parentFi.FieldType.GetField(arr[1], BindingFlags.NonPublic | BindingFlags.Instance);
1089 ····················Type childType = childFi.FieldType;
1090
1091 ····················// Don't initialize value types, if DBNull is stored in the field.
1092 ····················// Exception: DateTime and Guid.
1093 ····················if (o == DBNull.Value && childType.IsValueType
1094 ························&& childType != typeof(Guid)
1095 ························&& childType != typeof(DateTime))
1096 ························continue;
1097
1098 ····················if (childType == typeof(DateTime))
1099 ····················{
1100 ························if (o == DBNull.Value)
1101 ····························o = DateTime.MinValue;
1102 ····················}
1103 ····················if (childType.IsClass)
1104 ····················{
1105 ························if (o == DBNull.Value)
1106 ····························o = null;
1107 ····················}
1108
1109 ····················if (childType == typeof (Guid))
1110 ····················{
1111 ························if (o == DBNull.Value)
1112 ····························o = Guid.Empty;
1113 ························if (o is string)
1114 ························{
1115 ····························childFi.SetValue(parentOb, new Guid((string)o));
1116 ························}
1117 ························else if (o is Guid)
1118 ························{
1119 ····························childFi.SetValue(parentOb, o);
1120 ························}
1121 ························else if (o is byte[])
1122 ························{
1123 ····························childFi.SetValue(parentOb, new Guid((byte[])o));
1124 ························}
1125 ························else
1126 ····························throw new Exception(string.Format("Can't convert Guid field to column type {0}.", o.GetType().FullName));
1127 ····················}
1128 ····················else if (childType.IsSubclassOf(typeof(System.Enum)))
1129 ····················{
1130 ························object childOb = childFi.GetValue(parentOb);
1131 ························FieldInfo valueFi = childType.GetField("value__");
1132 ························valueFi.SetValue(childOb, o);
1133 ························childFi.SetValue(parentOb, childOb);
1134 ····················}
1135 ····················else
1136 ····················{
1137 ························childFi.SetValue(parentOb, o);
1138 ····················}
1139 ················}
1140 ················catch (Exception ex)
1141 ················{
1142 ····················string msg = "Error while writing the embedded object {0} of an object of type {1}. Check your mapping file.\n{2}";
1143
1144 ····················throw new NDOException(68, string.Format(msg, s, pc.GetType().FullName, ex.Message));
1145 ················}
1146
1147 ············}
1148 ············
1149 ············try
1150 ············{
1151 ················if (cl.HasEncryptedFields)
1152 ················{
1153 ····················foreach (var field in cl.Fields.Where( f => f.Encrypted ))
1154 ····················{
1155 ························string name = field.Column.Name;
1156 ························string s = (string) row[name];
1157 ························string es = AesHelper.Decrypt( s, EncryptionKey );
1158 ························row[name] = es;
1159 ····················}
1160 ················}
1161 ················pc.NDORead(row, fieldNames, startIndex);
1162 ············}
1163 ············catch (Exception ex)
1164 ············{
1165 ················throw new NDOException(69, "Error while writing to a field of an object of type " + pc.GetType().FullName + ". Check your mapping file.\n"
1166 ····················+ ex.Message);
1167 ············}
1168 ········}
1169
1170 ········/// <summary>
1171 ········/// Executes a sql script to generate the database tables.
1172 ········/// The function will execute any sql statements in the script
1173 ········/// which are valid according to the
1174 ········/// rules of the underlying database. Result sets are ignored.
1175 ········/// </summary>
1176 ········/// <param name="scriptFile">The script file to execute.</param>
1177 ········/// <param name="conn">A connection object, containing the connection
1178 ········/// string to the database, which should be altered.</param>
1179 ········/// <returns>A string array with error messages or the string "OK" for each of the statements in the file.</returns>
1180 ········/// <remarks>
1181 ········/// If the Connection object is invalid or null, a NDOException with ErrorNumber 44 will be thrown.
1182 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1183 ········/// Their message property will appear in the result array.
1184 ········/// If the script doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1185 ········/// </remarks>
1186 ········public string[] BuildDatabase( string scriptFile, Connection conn )
1187 ········{
1188 ············return BuildDatabase( scriptFile, conn, Encoding.UTF8 );
1189 ········}
1190
1191 ········/// <summary>
1192 ········/// Executes a sql script to generate the database tables.
1193 ········/// The function will execute any sql statements in the script
1194 ········/// which are valid according to the
1195 ········/// rules of the underlying database. Result sets are ignored.
1196 ········/// </summary>
1197 ········/// <param name="scriptFile">The script file to execute.</param>
1198 ········/// <param name="conn">A connection object, containing the connection
1199 ········/// string to the database, which should be altered.</param>
1200 ········/// <param name="encoding">The encoding of the script file. Default is UTF8.</param>
1201 ········/// <returns>A string array with error messages or the string "OK" for each of the statements in the file.</returns>
1202 ········/// <remarks>
1203 ········/// If the Connection object is invalid or null, a NDOException with ErrorNumber 44 will be thrown.
1204 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1205 ········/// Their message property will appear in the result array.
1206 ········/// If the script doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1207 ········/// </remarks>
1208 ········public string[] BuildDatabase(string scriptFile, Connection conn, Encoding encoding)
1209 ········{
1210 ············StreamReader sr = new StreamReader(scriptFile, encoding);
1211 ············string s = sr.ReadToEnd();
1212 ············sr.Close();
1213 ············string[] arr = s.Split(';');
1214 ············string last = arr[arr.Length - 1];
1215 ············bool lastInvalid = (last == null || last.Trim() == string.Empty);
1216 ············string[] result = new string[arr.Length - (lastInvalid ? 1 : 0)];
1217 ············using (var handler = GetSqlPassThroughHandler())
1218 ············{
1219 ················int i = 0;
1220 ················string ok = "OK";
1221 ················foreach (string statement in arr)
1222 ················{
1223 ····················if (statement != null && statement.Trim() != string.Empty)
1224 ····················{
1225 ························try
1226 ························{
1227 ····························handler.Execute(statement);
1228 ····························result[i] = ok;
1229 ························}
1230 ························catch (Exception ex)
1231 ························{
1232 ····························result[i] = ex.Message;
1233 ························}
1234 ····················}
1235 ····················i++;
1236 ················}
1237 ················CheckEndTransaction(true);
1238 ············}
1239 ············return result;
1240 ········}
1241
1242 ········/// <summary>
1243 ········/// Executes a sql script to generate the database tables.
1244 ········/// The function will execute any sql statements in the script
1245 ········/// which are valid according to the
1246 ········/// rules of the underlying database. Result sets are ignored.
1247 ········/// </summary>
1248 ········/// <param name="scriptFile">The script file to execute.</param>
1249 ········/// <returns></returns>
1250 ········/// <remarks>
1251 ········/// This function takes the first Connection object in the Connections list
1252 ········/// of the Mapping file und executes the script using that connection.
1253 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1254 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1255 ········/// Their message property will appear in the result array.
1256 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1257 ········/// </remarks>
1258 ········public string[] BuildDatabase(string scriptFile)
1259 ········{
1260 ············if (!File.Exists(scriptFile))
1261 ················throw new NDOException(48, "Script file " + scriptFile + " doesn't exist.");
1262 ············if (!this.mappings.Connections.Any())
1263 ················throw new NDOException(48, "Mapping file doesn't define a connection.");
1264 ············Connection conn = new Connection( this.mappings );
1265 ············Connection originalConnection = (Connection)this.mappings.Connections.First();
1266 ············conn.Name = OnNewConnection( originalConnection );
1267 ············conn.Type = originalConnection.Type;
1268 ············//Connection conn = (Connection) this.mappings.Connections[0];
1269 ············return BuildDatabase(scriptFile, conn);
1270 ········}
1271
1272 ········/// <summary>
1273 ········/// Executes a sql script to generate the database tables.
1274 ········/// The function will execute any sql statements in the script
1275 ········/// which are valid according to the
1276 ········/// rules of the underlying database. Result sets are ignored.
1277 ········/// </summary>
1278 ········/// <returns>
1279 ········/// A string array, containing the error messages produced by the statements
1280 ········/// contained in the script.
1281 ········/// </returns>
1282 ········/// <remarks>
1283 ········/// The sql script is assumed to be the executable name of the entry assembly with the
1284 ········/// extension .ndo.sql. Use BuildDatabase(string) to provide a path to a script.
1285 ········/// If the executable name can't be determined a NDOException with ErrorNumber 49 will be thrown.
1286 ········/// This function takes the first Connection object in the Connections list
1287 ········/// of the Mapping file und executes the script using that connection.
1288 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1289 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1290 ········/// Their message property will appear in the result array.
1291 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1292 ········/// </remarks>
1293 ········public string[] BuildDatabase()
1294 ········{
1295 ············Assembly ass = Assembly.GetEntryAssembly();
1296 ············if (ass == null)
1297 ················throw new NDOException(49, "Can't determine the path of the entry assembly - please pass a sql script path as argument to BuildDatabase.");
1298 ············string file = Path.ChangeExtension(ass.Location, ".ndo.sql");
1299 ············return BuildDatabase(file);
1300 ········}
1301
1302 ········/// <summary>
1303 ········/// Gets a SqlPassThroughHandler object which can be used to execute raw Sql statements.
1304 ········/// </summary>
1305 ········/// <param name="conn">Optional: The NDO-Connection to the database to be used.</param>
1306 ········/// <returns>An ISqlPassThroughHandler implementation</returns>
1307 ········public ISqlPassThroughHandler GetSqlPassThroughHandler( Connection conn = null )
1308 ········{
1309 ············if (!this.mappings.Connections.Any())
1310 ················throw new NDOException( 48, "Mapping file doesn't define a connection." );
1311 ············if (conn == null)
1312 ············{
1313 ················conn = new Connection( this.mappings );
1314 ················Connection originalConnection = (Connection) this.mappings.Connections.First();
1315 ················conn.Name = OnNewConnection( originalConnection );
1316 ················conn.Type = originalConnection.Type;
1317 ············}
1318
1319 ············return new SqlPassThroughHandler( this, conn );
1320 ········}
1321
1322 ········/// <summary>
1323 ········/// Gets a SqlPassThroughHandler object which can be used to execute raw Sql statements.
1324 ········/// </summary>
1325 ········/// <param name="predicate">A predicate defining which connection has to be used.</param>
1326 ········/// <returns>An ISqlPassThroughHandler implementation</returns>
1327 ········public ISqlPassThroughHandler GetSqlPassThroughHandler( Func<Connection, bool> predicate )
1328 ········{
1329 ············if (!this.mappings.Connections.Any())
1330 ················throw new NDOException( 48, "The Mapping file doesn't define a connection." );
1331 ············Connection conn = this.mappings.Connections.FirstOrDefault( predicate );
1332 ············if (conn == null)
1333 ················throw new NDOException( 48, "The Mapping file doesn't define a connection with this predicate." );
1334 ············return GetSqlPassThroughHandler( conn );
1335 ········}
1336
1337 ········/// <summary>
1338 ········/// Executes a xml script to generate the database tables.
1339 ········/// The function will generate and execute sql statements to perform
1340 ········/// the changes described by the xml.
1341 ········/// </summary>
1342 ········/// <returns></returns>
1343 ········/// <remarks>
1344 ········/// The script file is the first file found with the search string [AssemblyNameWithoutExtension].ndodiff.[SchemaVersion].xml.
1345 ········/// If several files match the search string biggest file name in the default sort order will be executed.
1346 ········/// This function takes the first Connection object in the Connections list
1347 ········/// of the Mapping file und executes the script using that connection.
1348 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1349 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1350 ········/// Their message property will appear in the result string array.
1351 ········/// If no script file exists, a NDOException with ErrorNumber 48 will be thrown.
1352 ········/// Note that an additional command is executed, which will update the NDOSchemaVersion entry.
1353 ········/// </remarks>
1354 ········public string[] PerformSchemaTransitions()
1355 ········{
1356 ············Assembly ass = Assembly.GetEntryAssembly();
1357 ············if (ass == null)
1358 ················throw new NDOException(49, "Can't determine the path of the entry assembly - please pass a sql script path as argument to PerformSchemaTransitions.");
1359 ············string mask = Path.GetFileNameWithoutExtension( ass.Location ) + ".ndodiff.*.xml";
1360 ············List<string> fileNames = Directory.GetFiles( Path.GetDirectoryName( ass.Location ), mask ).ToList();
1361 ············if (fileNames.Count == 0)
1362 ················return new String[] { String.Format( "No xml script file with a name like {0} found.", mask ) };
1363 ············if (fileNames.Count > 1)
1364 ················fileNames.Sort( ( fn1, fn2 ) => CompareFileName( fn1, fn2 ) );
1365 ············return PerformSchemaTransitions( fileNames[0] );
1366 ········}
1367
1368
1369 ········/// <summary>
1370 ········/// Executes a xml script to generate the database tables.
1371 ········/// The function will generate and execute sql statements to perform
1372 ········/// the changes described by the xml.
1373 ········/// </summary>
1374 ········/// <param name="scriptFile">The script file to execute.</param>
1375 ········/// <returns></returns>
1376 ········/// <remarks>
1377 ········/// This function takes the first Connection object in the Connections list
1378 ········/// of the Mapping file und executes the script using that connection.
1379 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1380 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1381 ········/// Their message property will appear in the result string array.
1382 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1383 ········/// Note that an additional command is executed, which will update the NDOSchemaVersion entry.
1384 ········/// </remarks>
1385 ········public string[] PerformSchemaTransitions(string scriptFile)
1386 ········{
1387 ············if (!File.Exists(scriptFile))
1388 ················throw new NDOException(48, "Script file " + scriptFile + " doesn't exist.");
1389
1390 ············if (!this.mappings.Connections.Any())
1391 ················throw new NDOException(48, "Mapping file doesn't define any connection.");
1392 ············Connection conn = new Connection( mappings );
1393 ············Connection originalConnection = mappings.Connections.First();
1394 ············conn.Name = OnNewConnection( originalConnection );
1395 ············conn.Type = originalConnection.Type;
1396 ············return PerformSchemaTransitions(scriptFile, conn);
1397 ········}
1398
1399
1400 ········int CompareFileName( string fn1, string fn2)
1401 ········{
1402 ············Regex regex = new Regex( @"ndodiff\.(.+)\.xml" );
1403 ············Match match = regex.Match( fn1 );
1404 ············string v1 = match.Groups[1].Value;
1405 ············match = regex.Match( fn2 );
1406 ············string v2 = match.Groups[1].Value;
1407 ············return new Version( v2 ).CompareTo( new Version( v1 ) );
1408 ········}
1409
1410 ········Guid[] GetSchemaIds(Connection ndoConn, string schemaName, IProvider provider)
1411 ········{
1412 ············var connection = provider.NewConnection( ndoConn.Name );
1413 ············var resultList = new List<Guid>();
1414
1415 ············using (var handler = GetSqlPassThroughHandler())
1416 ············{
1417 ················string[] TableNames = provider.GetTableNames( connection );
1418 ················if (TableNames.Any( t => String.Compare( t, "NDOSchemaIds", true ) == 0 ))
1419 ················{
1420 ····················var schemaIds = provider.GetQualifiedTableName("NDOSchemaIds");
1421 ····················var sn = provider.GetQuotedName("SchemaName");
1422 ····················var id = provider.GetQuotedName("Id");
1423 ····················string sql = $"SELECT {id} from {schemaIds} WHERE {sn} ";
1424 ····················if (String.IsNullOrEmpty(schemaName))
1425 ························sql += "IS NULL;";
1426 ····················else
1427 ························sql += $"LIKE '{schemaName}'";
1428
1429 ····················using(IDataReader dr = handler.Execute(sql, true))
1430 ····················{
1431 ························while (dr.Read())
1432 ····························resultList.Add( dr.GetGuid( 0 ) );
1433 ····················}
1434 ················}
1435 ················else
1436 ················{
1437 ····················SchemaTransitionGenerator schemaTransitionGenerator = new SchemaTransitionGenerator( ProviderFactory, ndoConn.Type, this.mappings );
1438 ····················var gt = typeof(Guid);
1439 ····················var gtype = $"{gt.FullName},{ new AssemblyName( gt.Assembly.FullName ).Name }";
1440 ····················var st = typeof(String);
1441 ····················var stype = $"{st.FullName},{ new AssemblyName( st.Assembly.FullName ).Name }";
1442 ····················var dt = typeof(DateTime);
1443 ····················var dtype = $"{st.FullName},{ new AssemblyName( st.Assembly.FullName ).Name }";
1444 ····················string transition = $@"<NdoSchemaTransition>
1445 ····<CreateTable name=""NDOSchemaIds"">
1446 ······<CreateColumn name=""SchemaName"" type=""{stype}"" allowNull=""True"" />
1447 ······<CreateColumn name=""Id"" type=""{gtype}"" size=""36"" isPrimary=""True"" />
1448 ······<CreateColumn name=""InsertTime"" type=""{dtype}"" size=""36"" />
1449 ····</CreateTable>
1450 </NdoSchemaTransition>";
1451 ····················XElement transitionElement = XElement.Parse(transition);
1452
1453 ····················string sql = schemaTransitionGenerator.Generate( transitionElement );
1454 ····················handler.Execute(sql);
1455 ················}
1456 ················handler.CommitTransaction();
1457 ············}
1458
1459 ············return resultList.ToArray();
1460 ········}
1461
1462 ········/// <summary>
1463 ········/// Executes a xml script to generate the database tables.
1464 ········/// The function will generate and execute sql statements to perform
1465 ········/// the changes described by the xml.
1466 ········/// </summary>
1467 ········/// <param name="scriptFile">The xml script file.</param>
1468 ········/// <param name="ndoConn">The connection to be used to perform the schema changes.</param>
1469 ········/// <returns>A list of strings about the states of the different schema change commands.</returns>
1470 ········/// <remarks>Note that an additional command is executed, which will update the NDOSchemaVersion entry.</remarks>
1471 ········public string[] PerformSchemaTransitions(string scriptFile, Connection ndoConn)
1472 ········{
1473 ············string schemaName = null;
1474 ············// Gespeicherte Version ermitteln.
1475 ············XElement transitionElements = XElement.Load( scriptFile );
1476 ············if (transitionElements.Attribute( "schemaName" ) != null)
1477 ················schemaName = transitionElements.Attribute( "schemaName" ).Value;
1478
1479 ············IProvider provider = this.mappings.GetProvider( ndoConn );
1480 ············var installedIds = GetSchemaIds( ndoConn, schemaName, provider );
1481 ············var newIds = new List<Guid>();
1482 ············SchemaTransitionGenerator schemaTransitionGenerator = new SchemaTransitionGenerator( ProviderFactory, ndoConn.Type, this.mappings );
1483
1484 ············// dtLiteral contains the leading and trailing quotes
1485 ············var dtLiteral = provider.GetSqlLiteral( DateTime.Now );
1486 ············var ndoSchemaIds = provider.GetQualifiedTableName("NDOSchemaIds");
1487 ············var schName = provider.GetQuotedName("SchemaName");
1488 ············var idCol = provider.GetQuotedName("Id");
1489 ············var insertTime = provider.GetQuotedName("InsertTime");
1490 ············var results = new List<string>();
1491
1492 ············// Each transitionElement gets it's own transaction.
1493 ············// The insert into NDOSchemaIds is part of the transaction.
1494 ············// If an error occurs, InternalPerformSchemaTransitions aborts the transaction.
1495 ············foreach (XElement transitionElement in transitionElements.Elements( "NdoSchemaTransition" ))
1496 ············{
1497 ················var id = transitionElement.Attribute("id")?.Value;
1498 ················if (id == null)
1499 ····················continue;
1500 ················var gid = new Guid(id);
1501 ················if (installedIds.Contains( gid ))
1502 ····················continue;
1503
1504 ················var sb = new StringBuilder();
1505 ················sb.Append( schemaTransitionGenerator.Generate( transitionElement ) );
1506 ················newIds.Add( gid );
1507
1508 ················if (schemaName != null)
1509 ····················sb.Append( $"INSERT INTO {ndoSchemaIds} ({schName},{idCol},{insertTime}) VALUES ('{schemaName}','{gid}',{dtLiteral});" );
1510 ················else
1511 ····················sb.Append( $"INSERT INTO {ndoSchemaIds} ({schName},{idCol},{insertTime}) VALUES (NULL,'{gid}',{dtLiteral});" );
1512
1513 ················results.AddRange( InternalPerformSchemaTransitions( ndoConn, sb.ToString() ) );
1514 ············}
1515
1516 ············return results.ToArray();
1517 ········}
1518
1519 ········private string[] InternalPerformSchemaTransitions( Connection ndoConn, string sql )
1520 ········{
1521 ············string[] arr = sql.Split( ';' );
1522
1523 ············string last = arr[arr.Length - 1];
1524 ············bool lastInvalid = (last == null || last.Trim() == string.Empty);
1525 ············string[] result = new string[arr.Length - (lastInvalid ? 1 : 0)];
1526 ············int i = 0;
1527 ············string ok = "OK";
1528 ············using (var handler = GetSqlPassThroughHandler())
1529 ············{
1530 ················handler.BeginTransaction();
1531 ················var doCommit = true;
1532 ················foreach (string statement in arr)
1533 ················{
1534 ····················if (!String.IsNullOrWhiteSpace(statement))
1535 ····················{
1536 ························try
1537 ························{
1538 ····························handler.Execute( statement.Trim() );
1539 ····························result[i] = ok;
1540 ························}
1541 ························catch (Exception ex)
1542 ························{
1543 ····························result[i] = ex.Message;
1544 ····························doCommit = false;
1545 ························}
1546 ····················}
1547 ····················i++;
1548 ················}
1549 ················if (doCommit)
1550 ····················handler.CommitTransaction();
1551 ················else
1552 ····················AbortTransaction();
1553 ············}
1554
1555 ············return result;
1556 ········}
1557 ········
1558 ········/// <summary>
1559 ········/// Transfers Data from the object to the DataRow
1560 ········/// </summary>
1561 ········/// <param name="pc"></param>
1562 ········/// <param name="row"></param>
1563 ········/// <param name="fieldNames"></param>
1564 ········/// <param name="startIndex"></param>
1565 ········protected virtual void WriteObject(IPersistenceCapable pc, DataRow row, string[] fieldNames, int startIndex)
1566 ········{
1567 ············Class cl = GetClass( pc );
1568 ············try
1569 ············{
1570 ················pc.NDOWrite(row, fieldNames, startIndex);
1571 ················if (cl.HasEncryptedFields)
1572 ················{
1573 ····················foreach (var field in cl.Fields.Where( f => f.Encrypted ))
1574 ····················{
1575 ························string name = field.Column.Name;
1576 ························string s = (string) row[name];
1577 ························string es = AesHelper.Encrypt( s, EncryptionKey );
1578 ························row[name] = es;
1579 ····················}
1580 ················}
1581 ············}
1582 ············catch (Exception ex)
1583 ············{
1584 ················throw new NDOException(70, "Error while reading a field of an object of type " + pc.GetType().FullName + ". Check your mapping file.\n"
1585 ····················+ ex.Message);
1586 ············}
1587
1588 ············if (cl.TypeNameColumn != null)
1589 ············{
1590 ················Type t = pc.GetType();
1591 ················row[cl.TypeNameColumn.Name] = t.FullName + "," + t.Assembly.GetName().Name;
1592 ············}
1593
1594 ············var etypes = cl.EmbeddedTypes;
1595 ············foreach(string s in etypes)
1596 ············{
1597 ················try
1598 ················{
1599 ····················NDO.Mapping.Field f = cl.FindField(s);
1600 ····················if (f == null)
1601 ························continue;
1602 ····················string[] arr = s.Split('.');
1603 ····················// Suche Feld mit Namen arr[0] als object
1604 ····················BaseClassReflector bcr = new BaseClassReflector(pc.GetType());
1605 ····················FieldInfo parentFi = bcr.GetField(arr[0], BindingFlags.NonPublic | BindingFlags.Instance);
1606 ····················Object parentOb = parentFi.GetValue(pc);
1607 ····················if (parentOb == null)
1608 ························throw new Exception(String.Format("The field {0} is null. Initialize the field in your default constructor.", arr[0]));
1609 ····················// Suche darin das Feld mit Namen Arr[1]
1610 ····················FieldInfo childFi = parentFi.FieldType.GetField(arr[1], BindingFlags.NonPublic | BindingFlags.Instance);
1611 ····················object o = childFi.GetValue(parentOb);
1612 ····················if (o == null
1613 ························|| o is DateTime && (DateTime) o == DateTime.MinValue
1614 ························|| o is Guid && (Guid) o == Guid.Empty)
1615 ························o = DBNull.Value;
1616 ····················row[f.Column.Name] = o;
1617 ················}
1618 ················catch (Exception ex)
1619 ················{
1620 ····················string msg = "Error while reading the embedded object {0} of an object of type {1}. Check your mapping file.\n{2}";
1621
1622 ····················throw new NDOException(71, string.Format(msg, s, pc.GetType().FullName, ex.Message));
1623 ················}
1624 ············}
1625 ········}
1626
1627 ········/// <summary>
1628 ········/// Check, if the specific field is loaded. If not, LoadData will be called.
1629 ········/// </summary>
1630 ········/// <param name="o">The parent object.</param>
1631 ········/// <param name="fieldOrdinal">A number to identify the field.</param>
1632 ········public virtual void LoadField(object o, int fieldOrdinal)
1633 ········{
1634 ············IPersistenceCapable pc = CheckPc(o);
1635 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
1636 ············{
1637 ················LoadState ls = pc.NDOLoadState;
1638 ················if (ls.FieldLoadState != null)
1639 ················{
1640 ····················if (ls.FieldLoadState[fieldOrdinal])
1641 ························return;
1642 ················}
1643 ················else
1644 ················{
1645 ····················ls.FieldLoadState = new BitArray( GetClass( pc ).Fields.Count() );
1646 ················}
1647 ················LoadData(o);
1648 ········}
1649 ········}
1650
1651 #pragma warning disable 419
1652 ········/// <summary>
1653 ········/// Load the data of a persistent object. This forces the transition of the object state from hollow to persistent.
1654 ········/// </summary>
1655 ········/// <param name="o">The hollow object.</param>
1656 ········/// <remarks>Note, that the relations won't be resolved with this function, with one Exception: 1:1 relations without mapping table will be resolved during LoadData. In all other cases, use <see cref="LoadRelation">LoadRelation</see>, to force resolving a relation.<seealso cref="NDOObjectState"/></remarks>
1657 #pragma warning restore 419
1658 ········public void LoadData( object o )
1659 ········{
1660 ············LoadDataAsync( o ).ConfigureAwait( false ).GetAwaiter().GetResult();
1661 ········}
1662
1663 #pragma warning disable 419
1664 ········/// <summary>
1665 ········/// Load the data of a persistent object asynchronously. This forces the transition of the object state from hollow to persistent.
1666 ········/// </summary>
1667 ········/// <param name="o">The hollow object.</param>
1668 ········/// <param name="cancellationToken">A token to cancel the operation</param>
1669 ········/// <remarks>Note, that the relations won't be resolved with this function, with one Exception: 1:1 relations without mapping table will be resolved during LoadData. In all other cases, use <see cref="LoadRelationAsync(object, string, bool, CancellationToken)">LoadRelationAsync</see>, to force resolving a relation.<seealso cref="NDOObjectState"/></remarks>
1670 #pragma warning restore 419
1671 ········public virtual async Task LoadDataAsync( object o, CancellationToken cancellationToken = default )
1672 ········{
1673 ············using (EnterOperation())
1674 ············{
1675 ················await LoadDataInternalAsync( o, cancellationToken ).ConfigureAwait( false );
1676 ············}
1677 ········}
1678
1679 ········async Task LoadDataInternalAsync( object o, CancellationToken cancellationToken )
1680 ········{
1681 ············IPersistenceCapable pc = CheckPc(o);
1682 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Hollow, "Can only load hollow objects");
1683 ············if (pc.NDOObjectState != NDOObjectState.Hollow)
1684 ················return;
1685 ············Class cl = GetClass(pc);
1686 ············IQuery q;
1687 ············q = CreateOidQuery(pc, cl);
1688 ············cache.UpdateCache(pc); // Make sure the object is in the cache
1689
1690 ············var objects = await q.ExecuteAsync( cancellationToken ).ConfigureAwait( false );
1691 ············var count = objects.Count;
1692
1693 ············if (count > 1)
1694 ············{
1695 ················throw new NDOException( 72, "Load Data: " + count + " result objects with the same oid" );
1696 ············}
1697 ············else if (count == 0)
1698 ············{
1699 ················if (ObjectNotPresentEvent == null || !ObjectNotPresentEvent(pc))
1700 ················throw new NDOException( 72, "LoadData: Object " + pc.NDOObjectId.Dump() + " is not present in the database." );
1701 ············}
1702 ········}
1703
1704 ········/// <summary>
1705 ········/// Creates a new IQuery object for the given type
1706 ········/// </summary>
1707 ········/// <param name="t"></param>
1708 ········/// <param name="oql"></param>
1709 ········/// <param name="hollow"></param>
1710 ········/// <param name="queryLanguage"></param>
1711 ········/// <returns></returns>
1712 ········public IQuery NewQuery(Type t, string oql, bool hollow = false, QueryLanguage queryLanguage = QueryLanguage.NDOql)
1713 ········{
1714 ············Type template = typeof( NDOQuery<object> ).GetGenericTypeDefinition();
1715 ············Type qt = template.MakeGenericType( t );
1716 ············return (IQuery)Activator.CreateInstance( qt, this, oql, hollow, queryLanguage );
1717 ········}
1718
1719 ········private IQuery CreateOidQuery(IPersistenceCapable pc, Class cl)
1720 ········{
1721 ············ArrayList parameters = new ArrayList();
1722 ············string oql = "oid = {0}";
1723 ············IQuery q = NewQuery(pc.GetType(), oql, false);
1724 ············q.Parameters.Add( pc.NDOObjectId );
1725 ············q.AllowSubclasses = false;
1726 ············return q;
1727 ········}
1728
1729 ········/// <summary>
1730 ········/// Mark the object dirty. The current state is
1731 ········/// saved in a DataRow, which is stored in the DS. This is done, to allow easy rollback later. Also, the
1732 ········/// object is locked in the cache.
1733 ········/// </summary>
1734 ········/// <param name="pc"></param>
1735 ········internal virtual void MarkDirty(IPersistenceCapable pc)
1736 ········{
1737 ············if (pc.NDOObjectState != NDOObjectState.Persistent)
1738 ················return;
1739 ············SaveObjectState(pc);
1740 ············pc.NDOObjectState = NDOObjectState.PersistentDirty;
1741 ········}
1742
1743 ········/// <summary>
1744 ········/// Mark the object dirty, but make sure first, that the object is loaded.
1745 ········/// The current or loaded state is saved in a DataRow, which is stored in the DS.
1746 ········/// This is done, to allow easy rollback later. Also, the
1747 ········/// object is locked in the cache.
1748 ········/// </summary>
1749 ········/// <param name="pc"></param>
1750 ········internal void LoadAndMarkDirty(IPersistenceCapable pc)
1751 ········{
1752 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient, "Transient objects can't be marked as dirty.");
1753
1754 ············if(pc.NDOObjectState == NDOObjectState.Deleted)
1755 ············{
1756 ················throw new NDOException(73, "LoadAndMarkDirty: Access to deleted objects is not allowed.");
1757 ············}
1758
1759 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
1760 ················LoadData(pc);
1761
1762 ············// state is either (Created), Persistent, PersistentDirty
1763 ············if(pc.NDOObjectState == NDOObjectState.Persistent)
1764 ············{
1765 ················MarkDirty(pc);
1766 ············}
1767 ········}
1768
1769
1770
1771 ········/// <summary>
1772 ········/// Save current object state in DS and lock the object in the cache.
1773 ········/// The saved state can be used later to retrieve the original object value if the
1774 ········/// current transaction is aborted. Also the state of all relations (not related objects) is stored.
1775 ········/// </summary>
1776 ········/// <param name="pc">The object that should be saved</param>
1777 ········/// <param name="isDeleting">Determines, if the object is about being deletet.</param>
1778 ········/// <remarks>
1779 ········/// In a data row there are the following things:
1780 ········/// Item································Responsible for writing
1781 ········/// State (own, inherited, embedded)····WriteObject
1782 ········/// TimeStamp····························NDOPersistenceHandler
1783 ········/// Oid····································WriteId
1784 ········/// Foreign Keys and their Type Codes····WriteForeignKeys
1785 ········/// </remarks>
1786 ········protected virtual void SaveObjectState(IPersistenceCapable pc, bool isDeleting = false)
1787 ········{
1788 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Persistent, "Object must be unmodified and persistent but is " + pc.NDOObjectState);
1789 ············
1790 ············DataTable table = GetTable(pc);
1791 ············DataRow row = table.NewRow();
1792 ············Class cl = GetClass(pc);
1793 ············WriteObject(pc, row, cl.ColumnNames, 0);
1794 ············WriteIdToRow(pc, row);
1795 ············if (!isDeleting)
1796 ················WriteLostForeignKeysToRow(cl, pc, row);
1797 ············table.Rows.Add(row);
1798 ············row.AcceptChanges();
1799 ············
1800 ············var relations = CollectRelationStates(pc);
1801 ············cache.Lock(pc, row, relations);
1802 ········}
1803
1804 ········private void SaveFakeRow(IPersistenceCapable pc)
1805 ········{
1806 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Hollow, "Object must be hollow but is " + pc.NDOObjectState);
1807 ············
1808 ············DataTable table = GetTable(pc);
1809 ············DataRow row = table.NewRow();
1810 ············Class pcClass = GetClass(pc);
1811 ············row.SetColumnError(GetFakeRowOidColumnName(pcClass), hollowMarker);
1812 ············Class cl = GetClass(pc);
1813 ············//WriteObject(pc, row, cl.FieldNames, 0);
1814 ············WriteIdToRow(pc, row);
1815 ············table.Rows.Add(row);
1816 ············row.AcceptChanges();
1817 ············
1818 ············cache.Lock(pc, row, null);
1819 ········}
1820
1821 ········/// <summary>
1822 ········/// This defines one column of the row, in which we use the
1823 ········/// ColumnError property to determine, if the row is a fake row.
1824 ········/// </summary>
1825 ········/// <param name="pcClass"></param>
1826 ········/// <returns></returns>
1827 ········private string GetFakeRowOidColumnName(Class pcClass)
1828 ········{
1829 ············// In case of several OidColumns the first column defined in the mapping
1830 ············// will be the one, holding the fake row info.
1831 ············return ((OidColumn)pcClass.Oid.OidColumns[0]).Name;
1832 ········}
1833
1834 ········private bool IsFakeRow(Class cl, DataRow row)
1835 ········{
1836 ············return (row.GetColumnError(GetFakeRowOidColumnName(cl)) == hollowMarker);
1837 ········}
1838
1839 ········/// <summary>
1840 ········/// Make a list of objects persistent.
1841 ········/// </summary>
1842 ········/// <param name="list">the list of IPersistenceCapable objects</param>
1843 ········public void MakePersistent(System.Collections.IList list)
1844 ········{
1845 ············foreach (IPersistenceCapable pc in list)
1846 ············{
1847 ················MakePersistent(pc);
1848 ············}
1849 ········}
1850
1851 ········/// <summary>
1852 ········/// Save state of related objects in the cache. Only the list itself is duplicated and stored. The related objects are
1853 ········/// not duplicated.
1854 ········/// </summary>
1855 ········/// <param name="pc">the parent object of all relations</param>
1856 ········/// <returns></returns>
1857 ········protected internal virtual List<KeyValuePair<Relation,object>> CollectRelationStates(IPersistenceCapable pc)
1858 ········{
1859 ············// Save state of relations
1860 ············Class c = GetClass(pc);
1861 ············List<KeyValuePair<Relation, object>> relations = new List<KeyValuePair<Relation, object>>( c.Relations.Count());
1862 ············foreach(Relation r in c.Relations)
1863 ············{
1864 ················if (r.Multiplicity == RelationMultiplicity.Element)
1865 ················{
1866 ····················relations.Add( new KeyValuePair<Relation, object>( r, mappings.GetRelationField( pc, r.FieldName ) ) );
1867 ················}
1868 ················else
1869 ················{
1870 ····················IList l = mappings.GetRelationContainer(pc, r);
1871 ····················if(l != null)
1872 ····················{
1873 ························l = (IList) ListCloner.CloneList(l);
1874 ····················}
1875 ····················relations.Add( new KeyValuePair<Relation, object>( r, l ) );
1876 ················}
1877 ············}
1878
1879 ············return relations;
1880 ········}
1881
1882
1883 ········/// <summary>
1884 ········/// Restore the saved relations.··Note that the objects are not restored as this is handled transparently
1885 ········/// by the normal persistence mechanism. Only the number and order of objects are restored, e.g. the state,
1886 ········/// the list had at the beginning of the transaction.
1887 ········/// </summary>
1888 ········/// <param name="pc"></param>
1889 ········/// <param name="relations"></param>
1890 ········private void RestoreRelatedObjects(IPersistenceCapable pc, List<KeyValuePair<Relation, object>> relations )
1891 ········{
1892 ············Class c = GetClass(pc);
1893
1894 ············foreach(var entry in relations)
1895 ············{
1896 ················var r = entry.Key;
1897 ················if (r.Multiplicity == RelationMultiplicity.Element)
1898 ················{
1899 ····················mappings.SetRelationField(pc, r.FieldName, entry.Value);
1900 ················}
1901 ················else
1902 ················{
1903 ····················if (pc.NDOGetLoadState(r.Ordinal))
1904 ····················{
1905 ························// Help GC by clearing lists
1906 ························IList l = mappings.GetRelationContainer(pc, r);
1907 ························if(l != null)
1908 ························{
1909 ····························l.Clear();
1910 ························}
1911 ························// Restore relation
1912 ························mappings.SetRelationContainer(pc, r, (IList)entry.Value);
1913 ····················}
1914 ················}
1915 ············}
1916 ········}
1917
1918
1919 ········/// <summary>
1920 ········/// Generates a query for related objects without mapping table.
1921 ········/// Note: this function can't be called in polymorphic scenarios,
1922 ········/// since they need a mapping table.
1923 ········/// </summary>
1924 ········/// <returns></returns>
1925 ········async Task<IList> QueryRelatedObjectsAsync( IPersistenceCapable pc, Relation r, IList l, bool hollow, CancellationToken cancellationToken )
1926 ········{
1927 ············// At this point of execution we know,
1928 ············// that the target type is not polymorphic and is not 1:1.
1929
1930 ············// We can't fetch these objects with an NDOql query
1931 ············// since this would require a relation in the opposite direction
1932
1933 ············IList relatedObjects;
1934 ············if (l != null)
1935 ················relatedObjects = l;
1936 ············else
1937 ················relatedObjects = mappings.CreateRelationContainer( pc, r );
1938
1939 ············Type t = r.ReferencedType;
1940 ············Class cl = GetClass( t );
1941 ············var provider = cl.Provider;
1942
1943 ············StringBuilder sb = new StringBuilder("SELECT * FROM ");
1944 ············var relClass = GetClass( r.ReferencedType );
1945 ············sb.Append( GetClass( r.ReferencedType ).GetQualifiedTableName() );
1946 ············sb.Append( " WHERE " );
1947 ············int i = 0;
1948 ············List<object> parameters = new List<object>();
1949 ············new ForeignKeyIterator( r ).Iterate( delegate ( ForeignKeyColumn fkColumn, bool isLastElement )
1950 ·············· {
1951 ·················· sb.Append( fkColumn.GetQualifiedName(relClass) );
1952 ·················· sb.Append( " = {" );
1953 ·················· sb.Append(i);
1954 ·················· sb.Append( '}' );
1955 ·················· parameters.Add( pc.NDOObjectId.Id[i] );
1956 ·················· if (!isLastElement)
1957 ······················ sb.Append( " AND " );
1958 ·················· i++;
1959 ·············· } );
1960
1961 ············if (!(String.IsNullOrEmpty( r.ForeignKeyTypeColumnName )))
1962 ············{
1963 ················sb.Append( " AND " );
1964 ················sb.Append( provider.GetQualifiedTableName( relClass.TableName + "." + r.ForeignKeyTypeColumnName ) );
1965 ················sb.Append( " = " );
1966 ················sb.Append( pc.NDOObjectId.Id.TypeId );
1967 ············}
1968
1969 ············IQuery q = NewQuery( t, sb.ToString(), hollow, Query.QueryLanguage.Sql );
1970
1971 ············foreach (var p in parameters)
1972 ············{
1973 ················q.Parameters.Add( p );
1974 ············}
1975
1976 ············q.AllowSubclasses = false;··// Remember: polymorphic relations always have a mapping table
1977
1978 ············IList l2 = await q.ExecuteAsync( cancellationToken ).ConfigureAwait( false );
1979
1980 ············foreach (object o in l2)
1981 ················relatedObjects.Add( o );
1982
1983 ············return relatedObjects;
1984 ········}
1985
1986
1987 ········/// <summary>
1988 ········/// Resolves an relation. The loaded objects will be hollow.
1989 ········/// </summary>
1990 ········/// <param name="o">The parent object.</param>
1991 ········/// <param name="fieldName">The field name of the container or variable, which represents the relation.</param>
1992 ········/// <param name="hollow">True, if the fetched objects should be hollow.</param>
1993 ········/// <remarks>Note: 1:1 relations without mapping table will be resolved during the transition from the hollow to the persistent state. To force this transition, use the <see cref="LoadData">LoadData</see> function.<seealso cref="LoadData"/></remarks>
1994 ········public void LoadRelation(object o, string fieldName, bool hollow)
1995 ········{
1996 ············LoadRelationAsync( o, fieldName, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
1997 ········}
1998
1999 ········/// <summary>
2000 ········/// Resolves an relation asynchronously.
2001 ········/// </summary>
2002 ········/// <param name="o">The parent object.</param>
2003 ········/// <param name="fieldName">The field name of the container or variable, which represents the relation.</param>
2004 ········/// <param name="hollow">True, if the fetched objects should be hollow.</param>
2005 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2006 ········/// <remarks>Note: 1:1 relations without mapping table will be resolved during the transition from the hollow to the persistent state. To force this transition, use the <see cref="LoadDataAsync">LoadDataAsync</see> function.<seealso cref="LoadDataAsync"/></remarks>
2007 ········public virtual async Task LoadRelationAsync( object o, string fieldName, bool hollow, CancellationToken cancellationToken = default )
2008 ········{
2009 ············using (EnterOperation())
2010 ············{
2011 ················IPersistenceCapable pc = CheckPc(o);
2012 ················await LoadRelationInternalAsync( pc, fieldName, hollow, cancellationToken ).ConfigureAwait( false );
2013 ············}
2014 ········}
2015
2016 ········
2017
2018 ········internal IList LoadRelation(IPersistenceCapable pc, Relation r, bool hollow)
2019 ········{
2020 ············return LoadRelationAsync( pc, r, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
2021 ········}
2022
2023 ········internal async Task<IList> LoadRelationAsync( IPersistenceCapable pc, Relation r, bool hollow, CancellationToken cancellationToken = default )
2024 ········{
2025 ············using (EnterOperation())
2026 ············{
2027 ················return await LoadRelationCoreAsync( pc, r, hollow, cancellationToken ).ConfigureAwait( false );
2028 ············}
2029 ········}
2030
2031 ········async Task<IList> LoadRelationCoreAsync( IPersistenceCapable pc, Relation r, bool hollow, CancellationToken cancellationToken )
2032 ········{
2033 ············IList result = null;
2034
2035 ············if (pc.NDOObjectState == NDOObjectState.Created)
2036 ················return null;
2037
2038 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
2039 ················await LoadDataAsync( pc, cancellationToken ).ConfigureAwait( false );
2040
2041 ············if(r.MappingTable == null)
2042 ············{
2043 ················// 1:1 are loaded with LoadData
2044 ················if (r.Multiplicity == RelationMultiplicity.List)
2045 ················{
2046 ····················// Help GC by clearing lists
2047 ····················IList l = mappings.GetRelationContainer(pc, r);
2048 ····················if(l != null)
2049 ························l.Clear();
2050 ····················IList relatedObjects = await QueryRelatedObjectsAsync( pc, r, l, hollow, cancellationToken ).ConfigureAwait( false );
2051 ····················mappings.SetRelationContainer(pc, r, relatedObjects);
2052 ····················result = relatedObjects;
2053 ················}
2054 ············}
2055 ············else
2056 ············{
2057 ················DataTable dt = null;
2058
2059 ················using (IMappingTableHandler handler = PersistenceHandlerManager.GetPersistenceHandler( pc ).GetMappingTableHandler( r ))
2060 ················{
2061 ····················await CheckTransactionAsync( handler, r.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2062 ····················dt = await handler.FindRelatedObjectsAsync( pc.NDOObjectId, this.ds, cancellationToken ).ConfigureAwait( false );
2063 ················}
2064
2065 ················IList relatedObjects;
2066 ················if(r.Multiplicity == RelationMultiplicity.Element)
2067 ····················relatedObjects = GenericListReflector.CreateList(r.ReferencedType, dt.Rows.Count);
2068 ················else
2069 ················{
2070 ····················relatedObjects = mappings.GetRelationContainer(pc, r);
2071 ····················if(relatedObjects != null)
2072 ························relatedObjects.Clear();··// Objects will be reread
2073 ····················else
2074 ························relatedObjects = mappings.CreateRelationContainer(pc, r);
2075 ················}
2076 ····················
2077 ················foreach(DataRow objRow in dt.Rows)
2078 ················{
2079 ····················Type relType;
2080
2081 ····················if (r.MappingTable.ChildForeignKeyTypeColumnName != null)························
2082 ····················{
2083 ························object typeCodeObj = objRow[r.MappingTable.ChildForeignKeyTypeColumnName];
2084 ························if (typeCodeObj is System.DBNull)
2085 ····························throw new NDOException( 75, String.Format( "Can't resolve subclass type code of type {0} in relation '{1}' - the type code in the data row is null.", r.ReferencedTypeName, r.ToString() ) );
2086 ························relType = typeManager[(int)typeCodeObj];
2087 ························if (relType == null)
2088 ····························throw new NDOException(75, String.Format("Can't resolve subclass type code {0} of type {1} - check, if your NDOTypes.xml exists.", objRow[r.MappingTable.ChildForeignKeyTypeColumnName], r.ReferencedTypeName));
2089 ····················}························
2090 ····················else
2091 ····················{
2092 ························relType = r.ReferencedType;
2093 ····················}
2094
2095 ····················//TODO: Generic Types: Exctract the type description from the type name column
2096 ····················if (relType.IsGenericTypeDefinition)
2097 ························throw new NotImplementedException("NDO doesn't support relations to generic types via mapping tables.");
2098 ····················ObjectId id = ObjectIdFactory.NewObjectId(relType, GetClass(relType), objRow, r.MappingTable, this.typeManager);
2099 ····················IPersistenceCapable relObj = FindObject(id);
2100 ····················relatedObjects.Add(relObj);
2101 ················}····
2102 ················if (r.Multiplicity == RelationMultiplicity.Element)
2103 ················{
2104 ····················Debug.Assert(relatedObjects.Count <= 1, "NDO retrieved more than one object for relation with cardinality 1");
2105 ····················mappings.SetRelationField(pc, r.FieldName, relatedObjects.Count > 0 ? relatedObjects[0] : null);
2106 ················}
2107 ················else
2108 ················{
2109 ····················mappings.SetRelationContainer(pc, r, relatedObjects);
2110 ····················result = relatedObjects;
2111 ················}
2112 ············}
2113 ············// Mark relation as loaded
2114 ············pc.NDOSetLoadState(r.Ordinal, true);
2115 ············return result;
2116 ········}
2117
2118 ········/// <summary>
2119 ········/// Loads elements of a relation
2120 ········/// </summary>
2121 ········/// <param name="pc">The object which needs to load the relation</param>
2122 ········/// <param name="relationName">The name of the relation</param>
2123 ········/// <param name="hollow">Determines, if the related objects should be hollow.</param>
2124 ········internal IList LoadRelationInternal(IPersistenceCapable pc, string relationName, bool hollow)
2125 ········{
2126 ············return LoadRelationInternalAsync( pc, relationName, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
2127 ········}
2128
2129 ········internal async Task<IList> LoadRelationInternalAsync( IPersistenceCapable pc, string relationName, bool hollow, CancellationToken cancellationToken = default )
2130 ········{
2131 ············if (pc.NDOObjectState == NDOObjectState.Created)
2132 ················return null;
2133 ············Class cl = GetClass(pc);
2134
2135 ············Relation r = cl.FindRelation(relationName);
2136
2137 ············if ( r == null )
2138 ················throw new NDOException( 76, String.Format( "Error while loading related objects: Can't find relation mapping for the field {0}.{1}. Check your mapping file.", pc.GetType().FullName, relationName ) );
2139
2140 ············if ( pc.NDOGetLoadState( r.Ordinal ) )
2141 ················return null;
2142
2143 ············return await LoadRelationAsync( pc, r, hollow, cancellationToken ).ConfigureAwait( false );
2144 ········}
2145
2146 ········/// <summary>
2147 ········/// Load the related objects of a parent object. The current value of the relation is replaced by the
2148 ········/// a list of objects that has been read from the DB.
2149 ········/// </summary>
2150 ········/// <param name="pc">The parent object of the relations</param>
2151 ········/// <param name="row">A data row containing the state of the object</param>
2152 ········private void LoadRelated1To1Objects(IPersistenceCapable pc, DataRow row)
2153 ········{
2154 ············// Stripped down to only serve 1:1-Relations w/out mapping table
2155 ············Class cl = GetClass(pc);
2156 ············foreach(Relation r in cl.Relations)
2157 ············{
2158 ················if(r.MappingTable == null)
2159 ················{
2160 ····················if (r.Multiplicity == RelationMultiplicity.Element)
2161 ····················{
2162 ························bool isNull = false;
2163 ························foreach (ForeignKeyColumn fkColumn in r.ForeignKeyColumns)
2164 ························{
2165 ····························isNull = isNull || (row[fkColumn.Name] == DBNull.Value);
2166 ························}
2167 ························if (isNull)
2168 ························{
2169 ····························mappings.SetRelationField(pc, r.FieldName, null);
2170 ························}
2171 ························else
2172 ························{
2173 ····························Type relType;
2174 ····························if (r.HasSubclasses)
2175 ····························{
2176 ································object o = row[r.ForeignKeyTypeColumnName];
2177 ································if (o == DBNull.Value)
2178 ····································throw new NDOException(75, String.Format(
2179 ········································"Can't resolve subclass type code {0} of type {1} - type code value is DBNull.",
2180 ········································row[r.ForeignKeyTypeColumnName], r.ReferencedTypeName));
2181 ································relType = typeManager[(int)o];
2182 ····························}
2183 ····························else
2184 ····························{
2185 ································relType = r.ReferencedType;
2186 ····························}
2187 ····························if (relType == null)
2188 ····························{
2189 ································throw new NDOException(75, String.Format(
2190 ····································"Can't resolve subclass type code {0} of type {1} - check, if your mapping file is correct.",
2191 ····································row[r.ForeignKeyTypeColumnName], r.ReferencedTypeName));
2192 ····························}
2193 ····
2194 ····························int count = r.ForeignKeyColumns.Count();
2195 ····························object[] keydata = new object[count];
2196 ····························int i = 0;
2197 ····························foreach(ForeignKeyColumn fkColumn in r.ForeignKeyColumns)
2198 ····························{
2199 ································keydata[i++] = row[fkColumn.Name];
2200 ····························}
2201
2202 ····························Type oidType = relType;
2203 ····························if (oidType.IsGenericTypeDefinition)
2204 ································oidType = mappings.GetRelationFieldType(r);
2205
2206 ····························ObjectId childOid = ObjectIdFactory.NewObjectId(oidType, GetClass(relType), keydata, this.typeManager);
2207 ····························if(childOid.IsValid())
2208 ································mappings.SetRelationField(pc, r.FieldName, FindObject(childOid));
2209 ····························else
2210 ································mappings.SetRelationField(pc, r.FieldName, null);
2211
2212 ························}
2213 ························pc.NDOSetLoadState(r.Ordinal, true);
2214 ····················}
2215 ················}
2216 ············}
2217 ········}
2218
2219 ········
2220 ········/// <summary>
2221 ········/// Creates a new ObjectId with the same Key value as a given ObjectId.
2222 ········/// </summary>
2223 ········/// <param name="oid">An ObjectId, which Key value will be used to build the new ObjectId.</param>
2224 ········/// <param name="t">The type of the object, the id will belong to.</param>
2225 ········/// <returns>An object of type ObjectId, or ObjectId.InvalidId</returns>
2226 ········/// <remarks>If the type t doesn't have a mapping in the mapping file an Exception of type NDOException is thrown.</remarks>
2227 ········public ObjectId NewObjectId(ObjectId oid, Type t)
2228 ········{
2229 ············return new ObjectId(oid.Id, t);
2230 ········}
2231
2232 ········/*
2233 ········/// <summary>
2234 ········/// Creates a new ObjectId which can be used to retrieve objects from the database.
2235 ········/// </summary>
2236 ········/// <param name="keyData">The id, which will be used to search for the object in the database</param>
2237 ········/// <param name="t">The type of the object.</param>
2238 ········/// <returns>An object of type ObjectId, or ObjectId.InvalidId</returns>
2239 ········/// <remarks>The keyData parameter must be one of the types Int32, String, Byte[] or Guid. If keyData is null or the type of keyData is invalid the function returns ObjectId.InvalidId. If the type t doesn't have a mapping in the mapping file, an Exception of type NDOException is thrown.</remarks>
2240 ········public ObjectId NewObjectId(object keyData, Type t)
2241 ········{
2242 ············if (keyData == null || keyData == DBNull.Value)
2243 ················return ObjectId.InvalidId;
2244
2245 ············Class cl =··GetClass(t);············
2246 ············
2247 ············if (cl.Oid.FieldType == typeof(int))
2248 ················return new ObjectId(new Int32Key(t, (int)keyData));
2249 ············else if (cl.Oid.FieldType == typeof(string))
2250 ················return new ObjectId(new StringKey(t, (String) keyData));
2251 ············else if (cl.Oid.FieldType == typeof(Guid))
2252 ················if (keyData is string)
2253 ····················return new ObjectId(new GuidKey(t, new Guid((String) keyData)));
2254 ················else
2255 ····················return new ObjectId(new GuidKey(t, (Guid) keyData));
2256 ············else if (cl.Oid.FieldType == typeof(MultiKey))
2257 ················return new ObjectId(new MultiKey(t, (object[]) keyData));
2258 ············else
2259 ················return ObjectId.InvalidId;
2260 ········}
2261 ········*/
2262
2263
2264 ········/*
2265 ········ * ····················if (cl.Oid.FieldName != null && HasOwnerCreatedIds)
2266 ····················{
2267 ························// The column, which hold the oid gets overwritten, if
2268 ························// Oid.FieldName contains a value.
2269 */
2270 ········private void WriteIdFieldsToRow(IPersistenceCapable pc, DataRow row)
2271 ········{
2272 ············Class cl = GetClass(pc);
2273
2274 ············if (cl.Oid.IsDependent)
2275 ················return;
2276
2277 ············Key key = pc.NDOObjectId.Id;
2278
2279 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2280 ············{
2281 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2282 ················if (oidColumn.FieldName != null)
2283 ················{
2284 ····················row[oidColumn.Name] = key[i];
2285 ················}
2286 ············}
2287 ········}
2288
2289 ········private void WriteIdToRow(IPersistenceCapable pc, DataRow row)
2290 ········{
2291 ············NDO.Mapping.Class cl = GetClass(pc);
2292 ············ObjectId oid = pc.NDOObjectId;
2293
2294 ············if (cl.TimeStampColumn != null)
2295 ················row[cl.TimeStampColumn] = pc.NDOTimeStamp;
2296
2297 ············if (cl.Oid.IsDependent)··// Oid data is in relation columns
2298 ················return;
2299
2300 ············Key key = oid.Id;
2301
2302 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2303 ············{
2304 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2305 ················row[oidColumn.Name] = key[i];
2306 ············}
2307 ········}
2308
2309 ········private void ReadIdFromRow(IPersistenceCapable pc, DataRow row)
2310 ········{
2311 ············ObjectId oid = pc.NDOObjectId;
2312 ············NDO.Mapping.Class cl = GetClass(pc);
2313
2314 ············if (cl.Oid.IsDependent)··// Oid data is in relation columns
2315 ················return;
2316
2317 ············Key key = oid.Id;
2318
2319 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2320 ············{
2321 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2322 ················object o = row[oidColumn.Name];
2323 ················if (!(o is Int32) && !(o is Guid) && !(o is String) && !(o is Int64))
2324 ····················throw new NDOException(78, "ReadId: invalid Id Column type in " + oidColumn.Name + ": " + o.GetType().FullName);
2325 ················if (oidColumn.SystemType == typeof(Guid) && (o is String))
2326 ····················key[i] = new Guid((string)o);
2327 ················else
2328 ····················key[i] = o;
2329 ············}
2330
2331 ········}
2332
2333 ········private void ReadId (Cache.Entry e)
2334 ········{
2335 ············ReadIdFromRow(e.pc, e.row);
2336 ········}
2337
2338 ········private void WriteObject(IPersistenceCapable pc, DataRow row, string[] fieldNames)
2339 ········{
2340 ············WriteObject(pc, row, fieldNames, 0);
2341 ········}
2342
2343 ········private void ReadTimeStamp(Class cl, IPersistenceCapable pc, DataRow row)
2344 ········{
2345 ············if (cl.TimeStampColumn == null)
2346 ················return;
2347 ············object col = row[cl.TimeStampColumn];
2348 ············if (col is String)
2349 ················pc.NDOTimeStamp = new Guid(col.ToString());
2350 ············else
2351 ················pc.NDOTimeStamp = (Guid) col;
2352 ········}
2353
2354
2355
2356 ········private void ReadTimeStamp(Cache.Entry e)
2357 ········{
2358 ············IPersistenceCapable pc = e.pc;
2359 ············NDO.Mapping.Class cl = GetClass(pc);
2360 ············Debug.Assert(!IsFakeRow(cl, e.row));
2361 ············if (cl.TimeStampColumn == null)
2362 ················return;
2363 ············if (e.row[cl.TimeStampColumn] is String)
2364 ················e.pc.NDOTimeStamp = new Guid(e.row[cl.TimeStampColumn].ToString());
2365 ············else
2366 ················e.pc.NDOTimeStamp = (Guid) e.row[cl.TimeStampColumn];
2367 ········}
2368
2369 ········/// <summary>
2370 ········/// Determines, if any objects are new, changed or deleted.
2371 ········/// </summary>
2372 ········public virtual bool HasChanges
2373 ········{
2374 ············get
2375 ············{
2376 ················return cache.LockedObjects.Count > 0;
2377 ············}
2378 ········}
2379
2380 ········/// <summary>
2381 ········/// Do the update for all rows in the ds.
2382 ········/// </summary>
2383 ········/// <param name="types">Types with changes.</param>
2384 ········/// <param name="delete">True, if delete operations are to be performed.</param>
2385 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2386 ········/// <remarks>
2387 ········/// Delete and Insert/Update operations are to be separated to maintain the type order.
2388 ········/// </remarks>
2389 ········private async Task UpdateTypesAsync( IList types, bool delete, CancellationToken cancellationToken )
2390 ········{
2391 ············foreach(Type t in types)
2392 ············{
2393 ················//Debug.WriteLine("Update Deleted Objects: "··+ t.Name);
2394 ················using (IPersistenceHandler handler = PersistenceHandlerManager.GetPersistenceHandler( t ))
2395 ················{
2396 ····················await CheckTransactionAsync( handler, t, cancellationToken ).ConfigureAwait( false );
2397 ····················ConcurrencyErrorHandler ceh = new ConcurrencyErrorHandler(this.OnConcurrencyError);
2398 ····················handler.ConcurrencyError += ceh;
2399 ····················try
2400 ····················{
2401 ························DataTable dt = GetTable(t);
2402 ························if (delete)
2403 ····························await handler.UpdateDeletedObjectsAsync( dt, cancellationToken ).ConfigureAwait( false );
2404 ························else
2405 ····························await handler.UpdateAsync( dt, cancellationToken ).ConfigureAwait( false );
2406 ····················}
2407 ····················finally
2408 ····················{
2409 ························handler.ConcurrencyError -= ceh;
2410 ····················}
2411 ················}
2412 ············}
2413 ········}
2414
2415 ········internal async Task UpdateCreatedMappingTableEntriesAsync( CancellationToken cancellationToken )
2416 ········{
2417 ············foreach (MappingTableEntry e in createdMappingTableObjects)
2418 ············{
2419 ················if (!e.DeleteEntry)
2420 ····················WriteMappingTableEntry(e);
2421 ············}
2422 ············// Now update all mapping tables
2423 ············foreach (IMappingTableHandler handler in mappingHandler.Values)
2424 ············{
2425 ················await CheckTransactionAsync( handler, handler.Relation.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2426 ················await handler.UpdateAsync( ds, cancellationToken ).ConfigureAwait( false );
2427 ············}
2428 ········}
2429
2430 ········internal async Task UpdateDeletedMappingTableEntriesAsync( CancellationToken cancellationToken )
2431 ········{
2432 ············foreach (MappingTableEntry e in createdMappingTableObjects)
2433 ············{
2434 ················if (e.DeleteEntry)
2435 ····················WriteMappingTableEntry(e);
2436 ············}
2437 ············// Now update all mapping tables
2438 ············foreach (IMappingTableHandler handler in mappingHandler.Values)
2439 ············{
2440 ················await CheckTransactionAsync( handler, handler.Relation.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2441 ················await handler.UpdateAsync( ds, cancellationToken ).ConfigureAwait( false );
2442 ············}
2443 ········}
2444
2445 ········/// <summary>
2446 ········/// Save all changed object into the DataSet and update the DB.
2447 ········/// When a newly created object is written to DB, the key might change. Therefore,
2448 ········/// the id is updated and the object is removed and re-inserted into the cache.
2449 ········/// </summary>
2450 ········public void Save(bool deferCommit = false)
2451 ········{
2452 ············SaveAsync( deferCommit ).ConfigureAwait( false ).GetAwaiter().GetResult();
2453 ········}
2454
2455 ········/// <summary>
2456 ········/// Save all changed object into the DataSet and update the DB asynchronously.
2457 ········/// When a newly created object is written to DB, the key might change. Therefore,
2458 ········/// the id is updated and the object is removed and re-inserted into the cache.
2459 ········/// </summary>
2460 ········/// <param name="deferCommit">Determines, if the commit of the transaction should be deferred.</param>
2461 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2462 ········/// <remarks>
2463 ········/// User callbacks like CollisionEvent and OnSavedEvent might be called on a thread pool thread.
2464 ········/// </remarks>
2465 ········public virtual async Task SaveAsync( bool deferCommit = false, CancellationToken cancellationToken = default )
2466 ········{
2467 ············using (EnterOperation())
2468 ············{
2469 ················await SaveInternalAsync( deferCommit, cancellationToken ).ConfigureAwait( false );
2470 ············}
2471 ········}
2472
2473 ········async Task SaveInternalAsync( bool deferCommit, CancellationToken cancellationToken )
2474 ········{
2475 ············if (IsClosed)
2476 ················throw new ObjectDisposedException(GetType().Name);
2477
2478 ············this.DeferredMode = deferCommit;
2479 ············var htOnSaving = new HashSet<ObjectId>();
2480 ············for(;;)
2481 ············{
2482 ················// We need to work on a copy of the locked objects list,
2483 ················// since the handlers might add more objects to the cache
2484 ················var lockedObjects = cache.LockedObjects.ToList();
2485 ················int count = lockedObjects.Count;
2486 ················foreach(Cache.Entry e in lockedObjects)
2487 ················{
2488 ····················if (e.pc.NDOObjectState != NDOObjectState.Deleted)
2489 ····················{
2490 ························IPersistenceNotifiable ipn = e.pc as IPersistenceNotifiable;
2491 ························if (ipn != null)
2492 ························{
2493 ····························if (!htOnSaving.Contains(e.pc.NDOObjectId))
2494 ····························{
2495 ································ipn.OnSaving();
2496 ································htOnSaving.Add(e.pc.NDOObjectId);
2497 ····························}
2498 ························}
2499 ····················}
2500 ················}
2501 ················// The system is stable, if the count doesn't change
2502 ················if (cache.LockedObjects.Count == count)
2503 ····················break;
2504 ············}
2505
2506 ············if (this.OnSavingEvent != null)
2507 ············{
2508 ················IList onSavingObjects = new ArrayList(cache.LockedObjects.Count);
2509 ················foreach(Cache.Entry e in cache.LockedObjects)
2510 ····················onSavingObjects.Add(e.pc);
2511 ················OnSavingEvent(onSavingObjects);
2512 ············}
2513
2514 ············List<Type> types = new List<Type>();
2515 ············List<IPersistenceCapable> deletedObjects = new List<IPersistenceCapable>();
2516 ············List<IPersistenceCapable> hollowModeObjects = hollowMode ? new List<IPersistenceCapable>() : null;
2517 ············List<IPersistenceCapable> changedObjects = new List<IPersistenceCapable>();
2518 ············List<IPersistenceCapable> addedObjects = new List<IPersistenceCapable>();
2519 ············List<Cache.Entry> addedCacheEntries = new List<Cache.Entry>();
2520
2521 ············// Save current state in DataSet
2522 ············foreach (Cache.Entry e in cache.LockedObjects)
2523 ············{
2524 ················Type objType = e.pc.GetType();
2525
2526 ················if (objType.IsGenericType && !objType.IsGenericTypeDefinition)
2527 ····················objType = objType.GetGenericTypeDefinition();
2528
2529 ················Class cl = GetClass(e.pc);
2530 ················//Debug.WriteLine("Saving: " + objType.Name + " id = " + e.pc.NDOObjectId.Dump());
2531 ················if(!types.Contains(objType))
2532 ················{
2533 ····················//Debug.WriteLine("Added··type " + objType.Name);
2534 ····················types.Add(objType);
2535 ················}
2536 ················NDOObjectState objectState = e.pc.NDOObjectState;
2537 ················if(objectState == NDOObjectState.Deleted)
2538 ················{
2539 ····················deletedObjects.Add(e.pc);
2540 ················}
2541 ················else if(objectState == NDOObjectState.Created)
2542 ················{
2543 ····················WriteObject(e.pc, e.row, cl.ColumnNames);····················
2544 ····················WriteIdFieldsToRow(e.pc, e.row);··// If fields are mapped to Oid, write them into the row
2545 ····················WriteForeignKeysToRow(e.pc, e.row);
2546 ····················//····················Debug.WriteLine(e.pc.GetType().FullName);
2547 ····················//····················DataRow[] rows = new DataRow[cache.LockedObjects.Count];
2548 ····················//····················i = 0;
2549 ····················//····················foreach(Cache.Entry e2 in cache.LockedObjects)
2550 ····················//····················{
2551 ····················//························rows[i++] = e2.row;
2552 ····················//····················}
2553 ····················//····················System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("testCommand");
2554 ····················//····················new SqlDumper(new DebugLogAdapter(), NDOProviderFactory.Instance["Sql"], cmd, cmd, cmd, cmd).Dump(rows);
2555
2556 ····················addedCacheEntries.Add(e);
2557 ····················addedObjects.Add( e.pc );
2558 ····················//····················objectState = NDOObjectState.Persistent;
2559 ················}
2560 ················else
2561 ················{
2562 ····················if (e.pc.NDOObjectState == NDOObjectState.PersistentDirty)
2563 ························changedObjects.Add( e.pc );
2564 ····················WriteObject(e.pc, e.row, cl.ColumnNames);
2565 ····················WriteForeignKeysToRow(e.pc, e.row); ····················
2566 ················}
2567 ················if(hollowMode && (objectState == NDOObjectState.Persistent || objectState == NDOObjectState.Created || objectState == NDOObjectState.PersistentDirty) )
2568 ················{
2569 ····················hollowModeObjects.Add(e.pc);
2570 ················}
2571 ············}
2572
2573 ············// Before we delete any db rows, we have to make sure, to delete mapping
2574 ············// table entries first, which might have relations to the db rows to be deleted
2575 ············await UpdateDeletedMappingTableEntriesAsync( cancellationToken ).ConfigureAwait( false );
2576
2577 ············// Update DB
2578 ············if (ds.HasChanges())
2579 ············{
2580
2581 ················// We need the reversed update order for deletions.
2582 ················types.Sort( ( t1, t2 ) =>
2583 ················{
2584 ····················int i1 = mappings.GetUpdateOrder( t1 );
2585 ····················int i2 = mappings.GetUpdateOrder( t2 );
2586 ····················if (i1 < i2)
2587 ····················{
2588 ························if (!addedObjects.Any( pc => pc.GetType() == t1 ))
2589 ····························i1 += 100000;
2590 ····················}
2591 ····················else
2592 ····················{
2593 ························if (!addedObjects.Any( pc => pc.GetType() == t2 ))
2594 ····························i2 += 100000;
2595 ····················}
2596 ····················return i2 - i1;
2597 ················} );
2598
2599 ················// Delete records first
2600
2601 ················await UpdateTypesAsync( types, true, cancellationToken ).ConfigureAwait( false );
2602
2603 ················// Now do all other updates in correct order.
2604 ················types.Reverse();
2605
2606 ················await UpdateTypesAsync( types, false, cancellationToken ).ConfigureAwait( false );
2607 ················
2608 ················ds.AcceptChanges();
2609 ················if(createdDirectObjects.Count > 0)
2610 ················{
2611 ····················// Rewrite all children that have foreign keys to parents which have just been saved now.
2612 ····················// They must be written again to store the correct foreign keys.
2613 ····················foreach(IPersistenceCapable pc in createdDirectObjects)
2614 ····················{
2615 ························Class cl = GetClass(pc);
2616 ························DataRow r = this.cache.GetDataRow(pc);
2617 ························string fakeColumnName = GetFakeRowOidColumnName(cl);
2618 ························object o = r[fakeColumnName];
2619 ························r[fakeColumnName] = o;
2620 ····················}
2621
2622 ····················await UpdateTypesAsync( types, false, cancellationToken ).ConfigureAwait( false );
2623 ················}
2624
2625 ················// Because object id might have changed during DB insertion, re-register newly created objects in the cache.
2626 ················foreach(Cache.Entry e in addedCacheEntries)
2627 ················{
2628 ····················cache.DeregisterLockedObject(e.pc);
2629 ····················ReadId(e);
2630 ····················cache.RegisterLockedObject(e.pc, e.row, e.relations);
2631 ················}
2632
2633 ················// Now update all mapping tables. Because of possible subclasses, there is no
2634 ················// relation between keys in the dataset schema. Therefore, we can update mapping
2635 ················// tables only after all other objects have been written to ensure correct foreign keys.
2636 ················await UpdateCreatedMappingTableEntriesAsync( cancellationToken ).ConfigureAwait( false );
2637
2638 ················// The rows may contain now new Ids, which should be
2639 ················// stored in the lostRowInfo's before the rows get detached
2640 ················foreach(Cache.Entry e in cache.LockedObjects)
2641 ················{
2642 ····················if (e.row.RowState != DataRowState.Detached)
2643 ····················{
2644 ························IPersistenceCapable pc = e.pc;
2645 ························ReadLostForeignKeysFromRow(GetClass(pc), pc, e.row);
2646 ····················}
2647 ················}
2648
2649 ················ds.AcceptChanges();
2650 ············}
2651
2652 ············await EndSaveAsync( !deferCommit, cancellationToken ).ConfigureAwait( false );
2653
2654 ············foreach(IPersistenceCapable pc in deletedObjects)
2655 ············{
2656 ················MakeObjectTransient(pc, false);
2657 ············}
2658
2659 ············ds.Clear();
2660 ············mappingHandler.Clear();
2661 ············createdDirectObjects.Clear();
2662 ············createdMappingTableObjects.Clear();
2663 ············this.relationChanges.Clear();
2664
2665 ············if(hollowMode)
2666 ············{
2667 ················MakeHollow(hollowModeObjects);
2668 ············}
2669
2670 ············if (this.OnSavedEvent != null)
2671 ············{
2672 ················AuditSet auditSet = new AuditSet()
2673 ················{
2674 ····················ChangedObjects = changedObjects,
2675 ····················CreatedObjects = addedObjects,
2676 ····················DeletedObjects = deletedObjects
2677 ················};
2678 ················this.OnSavedEvent( auditSet );
2679 ············}
2680 ········}
2681
2682 ········private async Task EndSaveAsync( bool forceCommit, CancellationToken cancellationToken )
2683 ········{
2684 ············foreach(Cache.Entry e in cache.LockedObjects)
2685 ············{
2686 ················if (e.pc.NDOObjectState == NDOObjectState.Created || e.pc.NDOObjectState == NDOObjectState.PersistentDirty)
2687 ····················this.ReadTimeStamp(e);
2688 ················e.pc.NDOObjectState = NDOObjectState.Persistent;
2689 ············}
2690
2691 ············cache.UnlockAll();
2692
2693 ············await CheckEndTransactionAsync( forceCommit, cancellationToken ).ConfigureAwait( false );
2694 ········}
2695
2696 ········/// <summary>
2697 ········/// Write all foreign keys for 1:1-relations.
2698 ········/// </summary>
2699 ········/// <param name="pc">The persistent object.</param>
2700 ········/// <param name="pcRow">The DataRow of the pesistent object.</param>
2701 ········private void WriteForeignKeysToRow(IPersistenceCapable pc, DataRow pcRow)
2702 ········{
2703 ············foreach(Relation r in mappings.Get1to1Relations(pc.GetType()))
2704 ············{
2705 ················IPersistenceCapable relObj = (IPersistenceCapable)mappings.GetRelationField(pc, r.FieldName);
2706 ················bool isDependent = GetClass(pc).Oid.IsDependent;
2707
2708 ················if ( relObj != null )
2709 ················{
2710 ····················int i = 0;
2711 ····················foreach ( ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2712 ····················{
2713 ························pcRow[fkColumn.Name] = relObj.NDOObjectId.Id[i++];
2714 ····················}
2715 ····················if ( r.ForeignKeyTypeColumnName != null )
2716 ····················{
2717 ························pcRow[r.ForeignKeyTypeColumnName] = relObj.NDOObjectId.Id.TypeId;
2718 ····················}
2719 ················}
2720 ················else
2721 ················{
2722 ····················foreach ( ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2723 ····················{
2724 ························pcRow[fkColumn.Name] = DBNull.Value;
2725 ····················}
2726 ····················if ( r.ForeignKeyTypeColumnName != null )
2727 ····················{
2728 ························pcRow[r.ForeignKeyTypeColumnName] = DBNull.Value;
2729 ····················}
2730 ················}
2731 ············}
2732 ········}
2733
2734
2735
2736 ········/// <summary>
2737 ········/// Write a mapping table entry to it's corresponding table. This is a pair of foreign keys.
2738 ········/// </summary>
2739 ········/// <param name="e">the mapping table entry</param>
2740 ········private void WriteMappingTableEntry(MappingTableEntry e)
2741 ········{
2742 ············IPersistenceCapable pc = e.ParentObject;
2743 ············IPersistenceCapable relObj = e.RelatedObject;
2744 ············Relation r = e.Relation;
2745 ············DataTable dt = GetTable(r.MappingTable.TableName);
2746 ············DataRow row = dt.NewRow();
2747 ············int i = 0;
2748 ············foreach (ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2749 ············{
2750 ················row[fkColumn.Name] = pc.NDOObjectId.Id[i++];
2751 ············}
2752 ············i = 0;
2753 ············foreach (ForeignKeyColumn fkColumn in r.MappingTable.ChildForeignKeyColumns)
2754 ············{
2755 ················row[fkColumn.Name] = relObj.NDOObjectId.Id[i++];
2756 ············}
2757
2758 ············if (r.ForeignKeyTypeColumnName != null)
2759 ················row[r.ForeignKeyTypeColumnName] = pc.NDOObjectId.Id.TypeId;
2760 ············if (r.MappingTable.ChildForeignKeyTypeColumnName != null)
2761 ················row[r.MappingTable.ChildForeignKeyTypeColumnName] = relObj.NDOObjectId.Id.TypeId;
2762
2763 ············dt.Rows.Add(row);
2764 ············if(e.DeleteEntry)
2765 ············{
2766 ················row.AcceptChanges();
2767 ················row.Delete();
2768 ············}
2769
2770 ············IMappingTableHandler handler;
2771 ············if (!mappingHandler.TryGetValue( r, out handler ))
2772 ············{
2773 ················mappingHandler[r] = handler = PersistenceHandlerManager.GetPersistenceHandler( pc ).GetMappingTableHandler( r );
2774 ············}
2775 ········}
2776
2777
2778 ········/// <summary>
2779 ········/// Undo changes of a certain object
2780 ········/// </summary>
2781 ········/// <param name="o">Object to undo</param>
2782 ········public void Restore(object o)
2783 ········{············
2784 ············IPersistenceCapable pc = CheckPc(o);
2785 ············Cache.Entry e = null;
2786 ············foreach (Cache.Entry entry in cache.LockedObjects)
2787 ············{
2788 ················if (entry.pc == pc)
2789 ················{
2790 ····················e = entry;
2791 ····················break;
2792 ················}
2793 ············}
2794 ············if (e == null)
2795 ················return;
2796 ············Class cl = GetClass(e.pc);
2797 ············switch (pc.NDOObjectState)
2798 ············{
2799 ················case NDOObjectState.PersistentDirty:
2800 ····················ObjectListManipulator.Remove(createdDirectObjects, pc);
2801 ····················foreach(Relation r in cl.Relations)
2802 ····················{
2803 ························if (r.Multiplicity == RelationMultiplicity.Element)
2804 ························{
2805 ····························IPersistenceCapable subPc = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
2806 ····························if (subPc != null && cache.IsLocked(subPc))
2807 ································Restore(subPc);
2808 ························}
2809 ························else
2810 ························{
2811 ····························if (!pc.NDOGetLoadState(r.Ordinal))
2812 ································continue;
2813 ····························IList subList = (IList) mappings.GetRelationContainer(pc, r);
2814 ····························if (subList != null)
2815 ····························{
2816 ································foreach(IPersistenceCapable subPc2 in subList)
2817 ································{
2818 ····································if (cache.IsLocked(subPc2))
2819 ········································Restore(subPc2);
2820 ································}
2821 ····························}
2822 ························}
2823 ····················}
2824 ····················RestoreRelatedObjects(pc, e.relations);
2825 ····················e.row.RejectChanges();
2826 ····················ReadObject(pc, e.row, cl.ColumnNames, 0);
2827 ····················cache.Unlock(pc);
2828 ····················pc.NDOObjectState = NDOObjectState.Persistent;
2829 ····················break;
2830 ················case NDOObjectState.Created:
2831 ····················ReadObject(pc, e.row, cl.ColumnNames, 0);
2832 ····················cache.Unlock(pc);
2833 ····················MakeObjectTransient(pc, true);
2834 ····················break;
2835 ················case NDOObjectState.Deleted:
2836 ····················if (!this.IsFakeRow(cl, e.row))
2837 ····················{
2838 ························e.row.RejectChanges();
2839 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2840 ························e.pc.NDOObjectState = NDOObjectState.Persistent;
2841 ····················}
2842 ····················else
2843 ····················{
2844 ························e.row.RejectChanges();
2845 ························e.pc.NDOObjectState = NDOObjectState.Hollow;
2846 ····················}
2847 ····················cache.Unlock(pc);
2848 ····················break;
2849
2850 ············}
2851 ········}
2852
2853 ········/// <summary>
2854 ········/// Aborts a pending transaction without restoring the object state.
2855 ········/// </summary>
2856 ········/// <remarks>Supports both local and EnterpriseService Transactions.</remarks>
2857 ········public void AbortTransaction()
2858 ········{
2859 ············AbortTransactionAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
2860 ········}
2861
2862 ········/// <summary>
2863 ········/// Aborts a pending transaction asynchronously without restoring the object state.
2864 ········/// </summary>
2865 ········/// <remarks>The rollback can't be canceled, therefore there is no CancellationToken.</remarks>
2866 ········public virtual async Task AbortTransactionAsync()
2867 ········{
2868 ············await TransactionScope.DisposeAsync().ConfigureAwait( false );
2869 ········}
2870
2871 ········/// <summary>
2872 ········/// Rejects all changes and restores the original object state. Added Objects will be made transient.
2873 ········/// </summary>
2874 ········public void Abort()
2875 ········{
2876 ············AbortAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
2877 ········}
2878
2879 ········/// <summary>
2880 ········/// Rejects all changes and restores the original object state asynchronously. Added Objects will be made transient.
2881 ········/// </summary>
2882 ········/// <remarks>The rollback can't be canceled, therefore there is no CancellationToken.</remarks>
2883 ········public virtual async Task AbortAsync()
2884 ········{
2885 ············// RejectChanges of the DS cannot be called because newly added rows would be deleted,
2886 ············// and therefore, couldn't be restored. Instead we call RejectChanges() for each
2887 ············// individual row.
2888 ············createdDirectObjects.Clear();
2889 ············createdMappingTableObjects.Clear();
2890 ············ArrayList deletedObjects = new ArrayList();
2891 ············ArrayList hollowModeObjects = hollowMode ? new ArrayList() : null;
2892
2893 ············// Read all objects from DataSet
2894 ············foreach (Cache.Entry e in cache.LockedObjects)
2895 ············{
2896 ················//Debug.WriteLine("Reading: " + e.pc.GetType().Name);
2897
2898 ················Class cl = GetClass(e.pc);
2899 ················bool isFakeRow = this.IsFakeRow(cl, e.row);
2900 ················if (!isFakeRow)
2901 ················{
2902 ····················RestoreRelatedObjects(e.pc, e.relations);
2903 ················}
2904 ················else
2905 ················{
2906 ····················Debug.Assert(e.pc.NDOObjectState == NDOObjectState.Deleted, "Fake row objects can only exist in deleted state");
2907 ················}
2908
2909 ················switch(e.pc.NDOObjectState)
2910 ················{
2911 ····················case NDOObjectState.Created:
2912 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2913 ························deletedObjects.Add(e.pc);
2914 ························break;
2915
2916 ····················case NDOObjectState.PersistentDirty:
2917 ························e.row.RejectChanges();
2918 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2919 ························e.pc.NDOObjectState = NDOObjectState.Persistent;
2920 ························break;
2921
2922 ····················case NDOObjectState.Deleted:
2923 ························if (!isFakeRow)
2924 ························{
2925 ····························e.row.RejectChanges();
2926 ····························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2927 ····························e.pc.NDOObjectState = NDOObjectState.Persistent;
2928 ························}
2929 ························else
2930 ························{
2931 ····························e.row.RejectChanges();
2932 ····························e.pc.NDOObjectState = NDOObjectState.Hollow;
2933 ························}
2934 ························break;
2935
2936 ····················default:
2937 ························throw new InternalException(2082, "Abort(): wrong state detected: " + e.pc.NDOObjectState + " id = " + e.pc.NDOObjectId.Dump());
2938 ························//Debug.Assert(false, "Object with wrong state detected: " + e.pc.NDOObjectState);
2939 ························//break;
2940 ················}
2941 ················if(hollowMode && e.pc.NDOObjectState == NDOObjectState.Persistent)
2942 ················{
2943 ····················hollowModeObjects.Add(e.pc);
2944 ················}
2945 ············}
2946 ············cache.UnlockAll();
2947 ············foreach(IPersistenceCapable pc in deletedObjects)
2948 ············{
2949 ················MakeObjectTransient(pc, true);
2950 ············}
2951 ············ds.Clear();
2952 ············mappingHandler.Clear();
2953 ············if(hollowMode)
2954 ············{
2955 ················MakeHollow(hollowModeObjects);
2956 ············}
2957
2958 ············this.relationChanges.Clear();
2959
2960
2961 ············await AbortTransactionAsync().ConfigureAwait( false );
2962 ········}
2963
2964
2965 ········/// <summary>
2966 ········/// Reset object to its transient state and remove it from the cache. Optinally, remove the object id to
2967 ········/// disable future access.
2968 ········/// </summary>
2969 ········/// <param name="pc"></param>
2970 ········/// <param name="removeId">Indicates if the object id should be nulled</param>
2971 ········private void MakeObjectTransient(IPersistenceCapable pc, bool removeId)
2972 ········{
2973 ············cache.Deregister(pc);
2974 ············// MakeTransient doesn't remove the ID, because delete makes objects transient and we need the id for the ChangeLog············
2975 ············if(removeId)
2976 ············{
2977 ················pc.NDOObjectId = null;
2978 ············}
2979 ············pc.NDOObjectState = NDOObjectState.Transient;
2980 ············pc.NDOStateManager = null;
2981 ········}
2982
2983 ········/// <summary>
2984 ········/// Makes an object transient.
2985 ········/// The object can be used afterwards, but changes will not be saved in the database.
2986 ········/// </summary>
2987 ········/// <remarks>
2988 ········/// Only persistent or hollow objects can be detached. Hollow objects are loaded to ensure valid data.
2989 ········/// </remarks>
2990 ········/// <param name="o">The object to detach.</param>
2991 ········public void MakeTransient(object o)
2992 ········{
2993 ············IPersistenceCapable pc = CheckPc(o);
2994 ············if(pc.NDOObjectState != NDOObjectState.Persistent && pc.NDOObjectState··!= NDOObjectState.Hollow)
2995 ············{
2996 ················throw new NDOException(79, "MakeTransient: Illegal state '" + pc.NDOObjectState + "' for this operation");
2997 ············}
2998
2999 ············if(pc.NDOObjectState··== NDOObjectState.Hollow)
3000 ············{
3001 ················LoadData(pc);
3002 ············}
3003 ············MakeObjectTransient(pc, true);
3004 ········}
3005
3006
3007 ········/// <summary>
3008 ········/// Make all objects of a list transient.
3009 ········/// </summary>
3010 ········/// <param name="list">the list of transient objects</param>
3011 ········public void MakeTransient(System.Collections.IList list)
3012 ········{
3013 ············foreach (IPersistenceCapable pc in list)
3014 ················MakeTransient(pc);
3015 ········}
3016
3017 ········/// <summary>
3018 ········/// Remove an object from the DB. Note that the object itself is not destroyed and may still be used.
3019 ········/// </summary>
3020 ········/// <param name="o">The object to remove</param>
3021 ········public void Delete(object o)
3022 ········{
3023 ············IPersistenceCapable pc = CheckPc(o);
3024 ············if (pc.NDOObjectState == NDOObjectState.Transient)
3025 ············{
3026 ················throw new NDOException( 120, "Can't delete transient object" );
3027 ············}
3028 ············if (pc.NDOObjectState != NDOObjectState.Deleted)
3029 ············{
3030 ················Delete(pc, true);
3031 ············}
3032 ········}
3033
3034
3035 ········private void LoadAllRelations(object o)
3036 ········{
3037 ············IPersistenceCapable pc = CheckPc(o);
3038 ············Class cl = GetClass(pc);
3039 ············foreach(Relation r in cl.Relations)
3040 ············{
3041 ················if (!pc.NDOGetLoadState(r.Ordinal))
3042 ····················LoadRelation(pc, r, true);
3043 ············}
3044 ········}
3045
3046
3047 ········/// <summary>
3048 ········/// Remove an object from the DB. Note that the object itself is not destroyed and may still be used.
3049 ········/// </summary>
3050 ········/// <remarks>
3051 ········/// If checkAssoziations it true, the object cannot be deleted if it is part of a bidirectional assoziation.
3052 ········/// This is the case if delete was called from user code. Internally, an object may be deleted because it is called from
3053 ········/// the parent object.
3054 ········/// </remarks>
3055 ········/// <param name="pc">the object to remove</param>
3056 ········/// <param name="checkAssoziations">true if child of a composition can't be deleted</param>
3057 ········private void Delete(IPersistenceCapable pc, bool checkAssoziations)
3058 ········{
3059 ············//Debug.WriteLine("Delete " + pc.NDOObjectId.Dump());
3060 ············//Debug.Indent();
3061 ············IDeleteNotifiable idn = pc as IDeleteNotifiable;
3062 ············if (idn != null)
3063 ················idn.OnDelete();
3064
3065 ············LoadAllRelations(pc);
3066 ············DeleteRelatedObjects(pc, checkAssoziations);
3067
3068 ············switch(pc.NDOObjectState)
3069 ············{
3070 ················case NDOObjectState.Transient:
3071 ····················throw new NDOException(80, "Cannot delete transient object: " + pc.NDOObjectId);
3072
3073 ················case NDOObjectState.Created:
3074 ····················DataRow row = cache.GetDataRow(pc);
3075 ····················row.Delete();
3076 ····················ArrayList cdosToDelete = new ArrayList();
3077 ····················foreach (IPersistenceCapable cdo in createdDirectObjects)
3078 ························if ((object)cdo == (object)pc)
3079 ····························cdosToDelete.Add(cdo);
3080 ····················foreach (object o in cdosToDelete)
3081 ························ObjectListManipulator.Remove(createdDirectObjects, o);
3082 ····················MakeObjectTransient(pc, true);
3083 ····················break;
3084 ················case NDOObjectState.Persistent:
3085 ····················if (!cache.IsLocked(pc)) // Deletes k�nnen durchaus mehrmals aufgerufen werden
3086 ························SaveObjectState(pc, true);
3087 ····················row = cache.GetDataRow(pc);
3088 ····················row.Delete();
3089 ····················pc.NDOObjectState = NDOObjectState.Deleted;
3090 ····················break;
3091 ················case NDOObjectState.Hollow:
3092 ····················if (!cache.IsLocked(pc)) // Deletes k�nnen durchaus mehrmals aufgerufen werden
3093 ························SaveFakeRow(pc);
3094 ····················row = cache.GetDataRow(pc);
3095 ····················row.Delete();
3096 ····················pc.NDOObjectState = NDOObjectState.Deleted;
3097 ····················break;
3098
3099 ················case NDOObjectState.PersistentDirty:
3100 ····················row = cache.GetDataRow(pc);
3101 ····················row.Delete();
3102 ····················pc.NDOObjectState··= NDOObjectState.Deleted;
3103 ····················break;
3104
3105 ················case NDOObjectState.Deleted:
3106 ····················break;
3107 ············}
3108
3109 ············//Debug.Unindent();
3110 ········}
3111
3112
3113 ········private void DeleteMappingTableEntry(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3114 ········{
3115 ············MappingTableEntry mte = null;
3116 ············foreach(MappingTableEntry e in createdMappingTableObjects)
3117 ············{
3118 ················if(e.ParentObject.NDOObjectId == pc.NDOObjectId && e.RelatedObject.NDOObjectId == child.NDOObjectId && e.Relation == r)
3119 ················{
3120 ····················mte = e;
3121 ····················break;
3122 ················}
3123 ············}
3124
3125 ············if(pc.NDOObjectState == NDOObjectState.Created || child.NDOObjectState == NDOObjectState.Created)
3126 ············{
3127 ················if (mte != null)
3128 ····················createdMappingTableObjects.Remove(mte);
3129 ············}
3130 ············else
3131 ············{
3132 ················if (mte == null)
3133 ····················createdMappingTableObjects.Add(new MappingTableEntry(pc, child, r, true));
3134 ············}
3135 ········}
3136
3137 ········private void DeleteOrNullForeignRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3138 ········{
3139 ············// Two tasks: a) Null the foreign key
3140 ············//··············b) remove the element from the foreign container
3141
3142 ············if (!r.Bidirectional)
3143 ················return;
3144
3145 ············// this keeps the oid valid
3146 ············if (GetClass(child.GetType()).Oid.IsDependent)
3147 ················return;
3148
3149 ············if(r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
3150 ············{
3151 ················LoadAndMarkDirty(child);
3152 ················mappings.SetRelationField(child, r.ForeignRelation.FieldName, null);
3153 ············}
3154 ············else //if(r.Multiplicity == RelationMultiplicity.List &&
3155 ················// r.ForeignRelation.Multiplicity == RelationMultiplicity.List)··
3156 ············{
3157 ················if (!child.NDOGetLoadState(r.ForeignRelation.Ordinal))
3158 ····················LoadRelation(child, r.ForeignRelation, true);
3159 ················IList l = mappings.GetRelationContainer(child, r.ForeignRelation);
3160 ················if (l == null)
3161 ····················throw new NDOException(67, "Can't remove object from the list " + child.GetType().FullName + "." + r.ForeignRelation.FieldName + ". The list is null.");
3162 ················ObjectListManipulator.Remove(l, pc);
3163 ················// Don't need to delete the mapping table entry, because that was done
3164 ················// through the parent.
3165 ············}
3166 ········}
3167
3168 ········private void DeleteOrNullRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3169 ········{
3170 ············// 1) Element····nomap····ass
3171 ············// 2) Element····nomap····comp
3172 ············// 3) Element····map········ass
3173 ············// 4) Element····map········comp
3174 ············// 5) List········nomap····ass
3175 ············// 6) List········nomap····comp
3176 ············// 7) List········map········ass
3177 ············// 8) List········map········comp
3178
3179 ············// Two tasks: Null foreign key and, if Composition, delete the child
3180
3181 ············// If Mapping Table, delete the entry - 3,7
3182 ············// If List and assoziation, null the foreign key in the foreign class - 5
3183 ············// If Element, null the foreign key in the own class 1,2,3,4
3184 ············// If composition, delete the child 2,4,6,8
3185
3186 ············// If the relObj is newly created
3187 ············ObjectListManipulator.Remove(createdDirectObjects, child);
3188 ············Class childClass = GetClass(child);
3189
3190 ············if (r.MappingTable != null)··// 3,7
3191 ············{················
3192 ················DeleteMappingTableEntry(pc, r, child);
3193 ············}
3194 ············else if (r.Multiplicity == RelationMultiplicity.List
3195 ················&& !r.Composition && !childClass.Oid.IsDependent) // 5
3196 ············{················
3197 ················LoadAndMarkDirty(child);
3198 ················DataRow row = this.cache.GetDataRow(child);
3199 ················foreach (ForeignKeyColumn fkColumnn in r.ForeignKeyColumns)
3200 ················{
3201 ····················row[fkColumnn.Name] = DBNull.Value;
3202 ····················child.NDOLoadState.ReplaceRowInfo(fkColumnn.Name, DBNull.Value);
3203 ················}
3204 ············}
3205 ············else if (r.Multiplicity == RelationMultiplicity.Element) // 1,2,3,4
3206 ············{
3207 ················LoadAndMarkDirty(pc);
3208 ············}
3209 ············if (r.Composition || childClass.Oid.IsDependent)
3210 ············{
3211 #if DEBUG
3212 ················if (child.NDOObjectState == NDOObjectState.Transient)
3213 ····················Debug.WriteLine("***** Object shouldn't be transient: " + child.GetType().FullName);
3214 #endif
3215 ················// Deletes the foreign key in case of List multiplicity
3216 ················// In case of Element multiplicity, the parent is either deleted,
3217 ················// or RemoveRelatedObject is called because the relation has been nulled.
3218 ················Delete(child);··
3219 ············}
3220 ········}
3221
3222 ········/// <summary>
3223 ········/// Remove a related object
3224 ········/// </summary>
3225 ········/// <param name="pc"></param>
3226 ········/// <param name="r"></param>
3227 ········/// <param name="child"></param>
3228 ········/// <param name="calledFromStateManager"></param>
3229 ········protected virtual void InternalRemoveRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable child, bool calledFromStateManager)
3230 ········{
3231 ············//TODO: We need a relation management, which is independent of
3232 ············//the state management of an object. At the moment the relation
3233 ············//lists or elements are cached for restore, if an object is marked dirty.
3234 ············//Thus we have to mark dirty our parent object in any case at the moment.
3235 ············if (calledFromStateManager)
3236 ················MarkDirty(pc);
3237
3238 ············// Object can be deleted in an OnDelete-Handler
3239 ············if (child.NDOObjectState == NDOObjectState.Deleted)
3240 ················return;
3241 ············//············Debug.WriteLine("InternalRemoveRelatedObject " + pc.GetType().Name + " " + r.FieldName + " " + child.GetType());
3242 ············// Preconditions
3243 ············// This is called either by DeleteRelatedObjects or by RemoveRelatedObject
3244 ············// The Object state is checked there
3245
3246 ············// If there is a composition in the opposite direction
3247 ············// && the other direction hasn't been processed
3248 ············// throw an exception.
3249 ············// If an exception is thrown at this point, have a look at IsLocked....
3250 ············if (r.Bidirectional && r.ForeignRelation.Composition
3251 ················&& !removeLock.IsLocked(child, r.ForeignRelation, pc))
3252 ················throw new NDOException(82, "Cannot remove related object " + child.GetType().FullName + " from parent " + pc.NDOObjectId.Dump() + ". Object must be removed through the parent.");
3253
3254 ············if (!removeLock.GetLock(pc, r, child))
3255 ················return;
3256
3257 ············try
3258 ············{
3259 ················// must be in this order, since the child
3260 ················// can be deleted in DeleteOrNullRelation
3261 ················//if (changeForeignRelations)
3262 ················DeleteOrNullForeignRelation(pc, r, child);
3263 ················DeleteOrNullRelation(pc, r, child);
3264 ············}
3265 ············finally
3266 ············{
3267 ················removeLock.Unlock(pc, r, child);
3268 ············}
3269
3270 ············this.relationChanges.Add( new RelationChangeRecord( pc, child, r.FieldName, false ) );
3271 ········}
3272
3273 ········private void DeleteRelatedObjects2(IPersistenceCapable pc, Class parentClass, bool checkAssoziations, Relation r)
3274 ········{
3275 ············//············Debug.WriteLine("DeleteRelatedObjects2 " + pc.GetType().Name + " " + r.FieldName);
3276 ············//············Debug.Indent();
3277 ············if (r.Multiplicity == RelationMultiplicity.Element)
3278 ············{
3279 ················IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
3280 ················if(child != null)
3281 ················{
3282 ····················//····················if(checkAssoziations && r.Bidirectional && !r.Composition)
3283 ····················//····················{
3284 ····················//························if (!r.ForeignRelation.Composition)
3285 ····················//························{
3286 ····················//····························mappings.SetRelationField(pc, r.FieldName, null);
3287 ····················//····························mappings.SetRelationField(child, r.ForeignRelation.FieldName, null);
3288 ····················//························}
3289 ····················//····························//System.Diagnostics.Debug.WriteLine("Nullen: pc = " + pc.GetType().Name + " child = " + child.GetType().Name);
3290 ····················//························else
3291 ····················//····························throw new NDOException(83, "Can't remove object of type " + pc.GetType().FullName + "; It is contained by an object of type " + child.GetType().FullName);
3292 ····················//····················}
3293 ····················InternalRemoveRelatedObject(pc, r, child, false);
3294 ················}
3295 ············}
3296 ············else
3297 ············{
3298 ················IList list = mappings.GetRelationContainer(pc, r);
3299 ················if(list != null && list.Count > 0)
3300 ················{
3301 ····················//····················if(checkAssoziations && r.Bidirectional && !r.Composition)
3302 ····················//····················{
3303 ····················//························throw new xxNDOException(84, "Cannot delete object " + pc.NDOObjectId + " in an assoziation. Remove related objects first.");
3304 ····················//····················}
3305 ····················// Since RemoveRelatedObjects probably changes the list,
3306 ····················// we iterate through a copy of the list.
3307 ····················ArrayList al = new ArrayList(list);
3308 ····················foreach(IPersistenceCapable relObj in al)
3309 ····················{
3310 ························InternalRemoveRelatedObject(pc, r, relObj, false);
3311 ····················}
3312 ················}
3313 ············}
3314 ············//············Debug.Unindent();
3315 ········}
3316
3317 ········/// <summary>
3318 ········/// Remove all related objects from a parent.
3319 ········/// </summary>
3320 ········/// <param name="pc">the parent object</param>
3321 ········/// <param name="checkAssoziations"></param>
3322 ········private void DeleteRelatedObjects(IPersistenceCapable pc, bool checkAssoziations)
3323 ········{
3324 ············//············Debug.WriteLine("DeleteRelatedObjects " + pc.NDOObjectId.Dump());
3325 ············//············Debug.Indent();
3326 ············// delete all related objects:
3327 ············Class parentClass = GetClass(pc);
3328 ············// Remove Assoziations first
3329 ············foreach(Relation r in parentClass.Relations)
3330 ············{
3331 ················if (!r.Composition)
3332 ····················DeleteRelatedObjects2(pc, parentClass, checkAssoziations, r);
3333 ············}
3334 ············foreach(Relation r in parentClass.Relations)
3335 ············{
3336 ················if (r.Composition)
3337 ····················DeleteRelatedObjects2(pc, parentClass, checkAssoziations, r);
3338 ············}
3339
3340 ············//············Debug.Unindent();
3341 ········}
3342
3343 ········/// <summary>
3344 ········/// Delete a list of objects
3345 ········/// </summary>
3346 ········/// <param name="list">the list of objects to remove</param>
3347 ········public void Delete(IList list)
3348 ········{
3349 ············for (int i = 0; i < list.Count; i++)
3350 ············{
3351 ················IPersistenceCapable pc = (IPersistenceCapable) list[i];
3352 ················Delete(pc);
3353 ············}
3354 ········}
3355
3356 ········/// <summary>
3357 ········/// Make object hollow. All relations will be unloaded and object data will be
3358 ········/// newly fetched during the next touch of a persistent field.
3359 ········/// </summary>
3360 ········/// <param name="o"></param>
3361 ········public virtual void MakeHollow(object o)
3362 ········{
3363 ············IPersistenceCapable pc = CheckPc(o);
3364 ············MakeHollow(pc, false);
3365 ········}
3366
3367 ········/// <summary>
3368 ········/// Make the object hollow if it is persistent. Unload all complex data.
3369 ········/// </summary>
3370 ········/// <param name="o"></param>
3371 ········/// <param name="recursive">if true then unload related objects as well</param>
3372 ········public virtual void MakeHollow(object o, bool recursive)
3373 ········{
3374 ············IPersistenceCapable pc = CheckPc(o);
3375 ············if(pc.NDOObjectState == NDOObjectState.Hollow)
3376 ················return;
3377 ············if(pc.NDOObjectState != NDOObjectState.Persistent)
3378 ············{
3379 ················throw new NDOException(85, "MakeHollow: Illegal state for this operation (" + pc.NDOObjectState.ToString() + ")");
3380 ············}
3381 ············pc.NDOObjectState = NDOObjectState.Hollow;
3382 ············MakeRelationsHollow(pc, recursive);
3383 ········}
3384
3385 ········/// <summary>
3386 ········/// Make all objects of a list hollow.
3387 ········/// </summary>
3388 ········/// <param name="list">the list of objects that should be made hollow</param>
3389 ········public virtual void MakeHollow(System.Collections.IList list)
3390 ········{
3391 ············MakeHollow(list, false);
3392 ········}
3393
3394 ········/// <summary>
3395 ········/// Make all objects of a list hollow.
3396 ········/// </summary>
3397 ········/// <param name="list">the list of objects that should be made hollow</param>
3398 ········/// <param name="recursive">if true then unload related objects as well</param>
3399 ········public void MakeHollow(System.Collections.IList list, bool recursive)
3400 ········{
3401 ············foreach (IPersistenceCapable pc in list)
3402 ················MakeHollow(pc, recursive);················
3403 ········}
3404
3405 ········/// <summary>
3406 ········/// Make all unlocked objects in the cache hollow.
3407 ········/// </summary>
3408 ········public virtual void MakeAllHollow()
3409 ········{
3410 ············foreach(var pc in cache.UnlockedObjects)
3411 ············{
3412 ················MakeHollow(pc, false);
3413 ············}
3414 ········}
3415
3416 ········/// <summary>
3417 ········/// Make relations hollow.
3418 ········/// </summary>
3419 ········/// <param name="pc">The parent object</param>
3420 ········/// <param name="recursive">If true, the function unloads related objects as well.</param>
3421 ········private void MakeRelationsHollow(IPersistenceCapable pc, bool recursive)
3422 ········{
3423 ············Class c = GetClass(pc);
3424 ············foreach(Relation r in c.Relations)
3425 ············{
3426 ················if (r.Multiplicity == RelationMultiplicity.Element)
3427 ················{
3428 ····················mappings.SetRelationField(pc, r.FieldName, null);
3429 ····················//····················IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
3430 ····················//····················if((null != child) && recursive)
3431 ····················//····················{
3432 ····················//························MakeHollow(child, true);
3433 ····················//····················}
3434 ················}
3435 ················else
3436 ················{
3437 ····················if (!pc.NDOGetLoadState(r.Ordinal))
3438 ························continue;
3439 ····················// Help GC by clearing lists
3440 ····················IList l = mappings.GetRelationContainer(pc, r);
3441 ····················if(l != null)
3442 ····················{
3443 ························if(recursive)
3444 ························{
3445 ····························MakeHollow(l, true);
3446 ························}
3447 ························l.Clear();
3448 ····················}
3449 ····················// Hollow relation
3450 ····················mappings.SetRelationContainer(pc, r, null);
3451 ················}
3452 ············}
3453 ············ClearRelationState(pc);
3454 ········}
3455
3456 ········private void ClearRelationState(IPersistenceCapable pc)
3457 ········{
3458 ············Class cl = GetClass(pc);
3459 ············foreach(Relation r in cl.Relations)
3460 ················pc.NDOSetLoadState(r.Ordinal, false);
3461 ········}
3462
3463 ········private void SetRelationState(IPersistenceCapable pc)
3464 ········{
3465 ············Class cl = GetClass(pc);
3466 ············// Due to a bug in the enhancer the constructors are not always patched right,
3467 ············// so NDOLoadState might be uninitialized
3468 ············if (pc.NDOLoadState == null)
3469 ············{
3470 ················FieldInfo fi = new BaseClassReflector(pc.GetType()).GetField("_ndoLoadState", BindingFlags.Instance | BindingFlags.NonPublic);
3471 ················if (fi == null)
3472 ····················throw new InternalException(3131, "pm.SetRelationState: No FieldInfo for _ndoLoadState");
3473 ················fi.SetValue(pc, new LoadState());
3474 ············}
3475
3476 ············// After serialization the relation load state is null
3477 ············if (pc.NDOLoadState.RelationLoadState == null)
3478 ················pc.NDOLoadState.RelationLoadState = new BitArray(LoadState.RelationLoadStateSize);
3479 ············foreach(Relation r in cl.Relations)
3480 ················pc.NDOSetLoadState(r.Ordinal, true);
3481 ········}
3482
3483 ········/// <summary>
3484 ········/// Creates an object of a given type and resolves constructor parameters using the container.
3485 ········/// </summary>
3486 ········/// <param name="t">The type of the persistent object</param>
3487 ········/// <returns></returns>
3488 ········public IPersistenceCapable CreateObject(Type t)
3489 ········{
3490 ············return (IPersistenceCapable) ActivatorUtilities.CreateInstance( ServiceProvider, t );
3491 ········}
3492
3493 ········/// <summary>
3494 ········/// Creates an object of a given type and resolves constructor parameters using the container.
3495 ········/// </summary>
3496 ········/// <typeparam name="T">The type of the object to create.</typeparam>
3497 ········/// <returns></returns>
3498 ········public T CreateObject<T>()
3499 ········{
3500 ············return (T)CreateObject( typeof( T ) );
3501 ········}
3502
3503 ········/// <summary>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3504 ········/// Gets the requested object. It first builds an ObjectId using the type and the
3505 ········/// key data. Then it uses FindObject to retrieve the object. No database access
3506 ········/// is performed.
3507 ········/// </summary>
3508 ········/// <param name="t">The type of the object to retrieve.</param>
3509 ········/// <param name="keyData">The key value to build the object id.</param>
3510 ········/// <returns>A hollow object</returns>
3511 ········/// <remarks>If the key value is of a wrong type, an exception will be thrown, if the object state changes from hollow to persistent.</remarks>
3512 ········public IPersistenceCapable FindObject(Type t, object keyData)
3513 ········{
3514 ············ObjectId oid = ObjectIdFactory.NewObjectId(t, GetClass(t), keyData, this.typeManager);
3515 ············return FindObject(oid);
3516 ········}
3517
3518 ········/// <summary>
3519 ········/// Finds an object using a short id.
3520 ········/// </summary>
3521 ········/// <param name="encodedShortId"></param>
3522 ········/// <returns></returns>
3523 ········public IPersistenceCapable FindObject(string encodedShortId)
3524 ········{
3525 ············string shortId = encodedShortId.Decode();
3526 ············string[] arr = shortId.Split( '-' );
3527 ············if (arr.Length != 3)
3528 ················throw new ArgumentException( "The format of the string is not valid", "shortId" );
3529 ············Type t = shortId.GetObjectType(this);··// try readable format
3530 ············if (t == null)
3531 ············{
3532 ················int typeCode = 0;
3533 ················if (!int.TryParse( arr[2], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out typeCode ))
3534 ····················throw new ArgumentException( "The string doesn't represent a loadable type", "shortId" );
3535 ················t = this.typeManager[typeCode];
3536 ················if (t == null)
3537 ····················throw new ArgumentException( "The string doesn't represent a loadable type", "shortId" );
3538 ············}
3539
3540 ············Class cls = GetClass( t );
3541 ············if (cls == null)
3542 ················throw new ArgumentException( "The type identified by the string is not persistent or is not managed by the given mapping file", "shortId" );
3543
3544 ············object[] keydata = new object[cls.Oid.OidColumns.Count];
3545 ············string[] oidValues = arr[2].Split( ' ' );
3546
3547 ············int i = 0;
3548 ············foreach (var oidValue in oidValues)
3549 ············{
3550 ················Type oidType = cls.Oid.OidColumns[i].SystemType;
3551 ················if (oidType == typeof( int ))
3552 ················{
3553 ····················int key;
3554 ····················if (!int.TryParse( oidValue, out key ))
3555 ························throw new ArgumentException( $"The ShortId value at index {i} doesn't contain an int value", nameof(encodedShortId) );
3556 ····················if (key > (int.MaxValue >> 1))
3557 ························key = -(int.MaxValue - key);
3558 ····················keydata[i] = key;
3559 ················}
3560 ················else if (oidType == typeof( Guid ))
3561 ················{
3562 ····················Guid key;
3563 ····················if (!Guid.TryParse( oidValue, out key ))
3564 ························throw new ArgumentException( $"The ShortId value at index {i} doesn't contain an Guid value", nameof( encodedShortId ) );
3565 ····················keydata[i] = key;
3566 ················}
3567 ················else if (oidType == typeof( string ))
3568 ················{
3569 ····················keydata[i] = oidValue;
3570 ················}
3571 ················else
3572 ················{
3573 ····················throw new ArgumentException( $"The oid type at index {i} of the persistent type {t} can't be used by a ShortId: {oidType.FullName}", nameof( encodedShortId ) );
3574 ················}
3575
3576 ················i++;
3577 ············}
3578
3579 ············if (keydata.Length == 1)
3580 ················return FindObject( t, keydata[0] );
3581
3582 ············return FindObject( t, keydata );············
3583 ········}
3584
3585 ········/// <summary>
3586 ········/// Gets the requested object. If it is in the cache, the cached object is returned, otherwise, a new (hollow)
3587 ········/// instance of the object is returned. In either case, the DB is not accessed!
3588 ········/// </summary>
3589 ········/// <param name="id">Object id</param>
3590 ········/// <returns>The object to retrieve in hollow state</returns>········
3591 ········public IPersistenceCapable FindObject(ObjectId id)
3592 ········{
3593 ············if(id == null)
3594 ············{
3595 ················throw new ArgumentNullException("id");
3596 ············}
3597
3598 ············if(!id.IsValid())
3599 ············{
3600 ················throw new NDOException(86, "FindObject: Invalid object id. Object does not exist");
3601 ············}
3602
3603 ············IPersistenceCapable pc = cache.GetObject(id);
3604 ············if(pc == null)
3605 ············{
3606 ················pc = CreateObject(id.Id.Type);
3607 ················pc.NDOObjectId = id;
3608 ················pc.NDOStateManager = sm;
3609 ················pc.NDOObjectState = NDOObjectState.Hollow;
3610 ················cache.UpdateCache(pc);
3611 ············}
3612 ············return pc;
3613 ········}
3614
3615
3616 ········/// <summary>
3617 ········/// Reload an object from the database.
3618 ········/// </summary>
3619 ········/// <param name="o">The object to be reloaded.</param>
3620 ········public void Refresh(object o)
3621 ········{
3622 ············RefreshAsync( o ).ConfigureAwait( false ).GetAwaiter().GetResult();
3623 ········}
3624
3625 ········/// <summary>
3626 ········/// Reload an object from the database asynchronously.
3627 ········/// </summary>
3628 ········/// <param name="o">The object to be reloaded.</param>
3629 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3630 ········public virtual async Task RefreshAsync( object o, CancellationToken cancellationToken = default )
3631 ········{
3632 ············using (EnterOperation())
3633 ············{
3634 ················await RefreshInternalAsync( o, cancellationToken ).ConfigureAwait( false );
3635 ············}
3636 ········}
3637
3638 ········async Task RefreshInternalAsync( object o, CancellationToken cancellationToken )
3639 ········{
3640 ············IPersistenceCapable pc = CheckPc(o);
3641 ············if(pc.NDOObjectState == NDOObjectState.Transient || pc.NDOObjectState == NDOObjectState.Deleted)
3642 ············{
3643 ················throw new NDOException(87, "Refresh: Illegal state " + pc.NDOObjectState + " for this operation");
3644 ············}
3645
3646 ············if(pc.NDOObjectState == NDOObjectState.Created || pc.NDOObjectState == NDOObjectState.PersistentDirty)
3647 ················return; // Cannot update objects in current transaction
3648
3649 ············MakeHollow(pc);
3650 ············await LoadDataAsync( pc, cancellationToken ).ConfigureAwait( false );
3651 ········}
3652
3653 ········/// <summary>
3654 ········/// Refresh a list of objects.
3655 ········/// </summary>
3656 ········/// <param name="list">The list of objects to be refreshed.</param>
3657 ········public void Refresh(IList list)
3658 ········{
3659 ············RefreshAsync( list ).ConfigureAwait( false ).GetAwaiter().GetResult();
3660 ········}
3661
3662 ········/// <summary>
3663 ········/// Refresh a list of objects asynchronously.
3664 ········/// </summary>
3665 ········/// <param name="list">The list of objects to be refreshed.</param>
3666 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3667 ········/// <remarks>The objects are refreshed sequentially.</remarks>
3668 ········public virtual async Task RefreshAsync( IList list, CancellationToken cancellationToken = default )
3669 ········{
3670 ············using (EnterOperation())
3671 ············{
3672 ················foreach (IPersistenceCapable pc in list)
3673 ····················await RefreshAsync( (object) pc, cancellationToken ).ConfigureAwait( false );
3674 ············}
3675 ········}
3676
3677 ········/// <summary>
3678 ········/// Refreshes all unlocked objects in the cache.
3679 ········/// </summary>
3680 ········public void RefreshAll()
3681 ········{
3682 ············RefreshAllAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
3683 ········}
3684
3685 ········/// <summary>
3686 ········/// Refreshes all unlocked objects in the cache asynchronously.
3687 ········/// </summary>
3688 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3689 ········public virtual Task RefreshAllAsync( CancellationToken cancellationToken = default )
3690 ········{
3691 ············return RefreshAsync( cache.UnlockedObjects.ToList(), cancellationToken );
3692 ········}
3693
3694 ········/// <summary>
3695 ········/// Closes the PersistenceManager and releases all resources.
3696 ········/// </summary>
3697 ········public override async Task CloseAsync()
3698 ········{
3699 ············if (this.isClosing)
3700 ················return;
3701 ············this.isClosing = true;
3702 ············await TransactionScope.DisposeAsync().ConfigureAwait( false );
3703 ············UnloadCache();
3704 ············await base.CloseAsync().ConfigureAwait( false );
3705 ········}
3706
3707 ········internal void LogIfVerbose( string msg )
3708 ········{
3709 ············if (Logger != null && Logger.IsEnabled( LogLevel.Debug ))
3710 ················Logger.LogDebug( msg );
3711 ········}
3712
3713
3714 ········#endregion
3715
3716
3717
3718 #region Query engine
3719
3720
3721 ········/// <summary>
3722 ········/// Returns a virtual table for Linq queries.
3723 ········/// </summary>
3724 ········/// <typeparam name="T"></typeparam>
3725 ········/// <returns></returns>
3726 ········public VirtualTable<T> Objects<T>() //where T: IPersistenceCapable
3727 ········{
3728 ············return new VirtualTable<T>( this );
3729 ········}
3730
3731 ········
3732 ········/// <summary>
3733 ········/// Suppose, you had a directed 1:n relation from class A to class B. If you load an object of type B,
3734 ········/// a foreign key pointing to a row in the table A is read as part of the B row. But since B doesn't have
3735 ········/// a relation to A the foreign key would get lost if we discard the row after building the B object. To
3736 ········/// not lose the foreign key it will be stored as part of the object.
3737 ········/// </summary>
3738 ········/// <param name="cl"></param>
3739 ········/// <param name="pc"></param>
3740 ········/// <param name="row"></param>
3741 ········void ReadLostForeignKeysFromRow(Class cl, IPersistenceCapable pc, DataRow row)
3742 ········{
3743 ············if (cl.FKColumnNames != null && pc.NDOLoadState != null)
3744 ············{
3745 ················//················Debug.WriteLine("GetLostForeignKeysFromRow " + pc.NDOObjectId.Dump());
3746 ················KeyValueList kvl = new KeyValueList(cl.FKColumnNames.Count());
3747 ················foreach(string colName in cl.FKColumnNames)
3748 ····················kvl.Add(new KeyValuePair(colName, row[colName]));
3749 ················pc.NDOLoadState.LostRowInfo = kvl;················
3750 ············}
3751 ········}
3752
3753 ········/// <summary>
3754 ········/// Writes information into the data row, which cannot be stored in the object.
3755 ········/// </summary>
3756 ········/// <param name="cl"></param>
3757 ········/// <param name="pc"></param>
3758 ········/// <param name="row"></param>
3759 ········protected virtual void WriteLostForeignKeysToRow(Class cl, IPersistenceCapable pc, DataRow row)
3760 ········{
3761 ············if (cl.FKColumnNames != null)
3762 ············{
3763 ················//················Debug.WriteLine("WriteLostForeignKeys " + pc.NDOObjectId.Dump());
3764 ················KeyValueList kvl = (KeyValueList)pc.NDOLoadState.LostRowInfo;
3765 ················if (kvl == null)
3766 ····················throw new NDOException(88, "Can't find foreign keys for the relations of the object " + pc.NDOObjectId.Dump());
3767 ················foreach (KeyValuePair pair in kvl)
3768 ····················row[(string) pair.Key] = pair.Value;
3769 ············}
3770 ········}
3771
3772 ········void Row2Object(Class cl, IPersistenceCapable pc, DataRow row)
3773 ········{
3774 ············ReadObject(pc, row, cl.ColumnNames, 0);
3775 ············ReadTimeStamp(cl, pc, row);
3776 ············ReadLostForeignKeysFromRow(cl, pc, row);
3777 ············LoadRelated1To1Objects(pc, row);
3778 ············pc.NDOObjectState = NDOObjectState.Persistent;
3779 ········}
3780
3781
3782 ········/// <summary>
3783 ········/// Convert a data table to objects. Note that the table might only hold objects of the specified type.
3784 ········/// </summary>
3785 ········internal IList DataTableToIList(Type t, ICollection rows, bool hollow)
3786 ········{
3787 ············IList queryResult = GenericListReflector.CreateList(t, rows.Count);
3788 ············if (rows.Count == 0)
3789 ················return queryResult;
3790
3791 ············IList callbackObjects = new ArrayList();
3792 ············Class cl = GetClass(t);
3793 ············if (t.IsGenericTypeDefinition)
3794 ············{
3795 ················if (cl.TypeNameColumn == null)
3796 ····················throw new NDOException(104, "No type name column defined for generic type '" + t.FullName + "'. Check your mapping file.");
3797 ················IEnumerator en = rows.GetEnumerator();
3798 ················en.MoveNext();··// Move to the first element
3799 ················DataRow testrow = (DataRow)en.Current;
3800 ················if (testrow.Table.Columns[cl.TypeNameColumn.Name] == null)
3801 ····················throw new InternalException(3333, "DataTableToIList: TypeNameColumn isn't defined in the schema.");
3802 ············}
3803
3804 ············foreach(DataRow row in rows)
3805 ············{
3806 ················Type concreteType = t;
3807 ················if (t.IsGenericTypeDefinition)··// type information is in the row
3808 ················{
3809 ····················if (row[cl.TypeNameColumn.Name] == DBNull.Value)
3810 ····················{
3811 ························ObjectId tempid = ObjectIdFactory.NewObjectId(t, cl, row, this.typeManager);
3812 ························throw new NDOException(105, "Null entry in the TypeNameColumn of the type '" + t.FullName + "'. Oid = " + tempid.ToString());
3813 ····················}
3814 ····················string typeStr = (string)row[cl.TypeNameColumn.Name];
3815 ····················concreteType = Type.GetType(typeStr);
3816 ····················if (concreteType == null)
3817 ························throw new NDOException(106, "Can't load generic type " + typeStr);
3818 ················}
3819 ················ObjectId id = ObjectIdFactory.NewObjectId(concreteType, cl, row, this.typeManager);
3820 ················IPersistenceCapable pc = cache.GetObject(id);················
3821 ················if(pc == null)
3822 ················{
3823 ····················pc = CreateObject( concreteType );
3824 ····················pc.NDOObjectId = id;
3825 ····················pc.NDOStateManager = sm;
3826 ····················// If the object shouldn't be hollow, this will be overwritten later.
3827 ····················pc.NDOObjectState = NDOObjectState.Hollow;
3828 ················}
3829 ················// If we have found a non hollow object, the time stamp remains the old one.
3830 ················// In every other case we use the new time stamp.
3831 ················// Note, that there could be a hollow object in the cache.
3832 ················// We need the time stamp in hollow objects in order to correctly
3833 ················// delete objects using fake rows.
3834 ················if (pc.NDOObjectState == NDOObjectState.Hollow)
3835 ················{
3836 ····················ReadTimeStamp(cl, pc, row);
3837 ················}
3838 ················if(!hollow && pc.NDOObjectState != NDOObjectState.PersistentDirty)
3839 ················{
3840 ····················Row2Object(cl, pc, row);
3841 ····················if ((pc as IPersistenceNotifiable) != null)
3842 ························callbackObjects.Add(pc);
3843 ················}
3844
3845 ················cache.UpdateCache(pc);
3846 ················queryResult.Add(pc);
3847 ············}
3848 ············// Make shure this is the last statement before returning
3849 ············// to the caller, so the user can recursively use persistent
3850 ············// objects
3851 ············foreach(IPersistenceNotifiable ipn in callbackObjects)
3852 ················ipn.OnLoaded();
3853
3854 ············return queryResult;
3855 ········}
3856
3857 #endregion
3858
3859 #region Cache Management
3860 ········/// <summary>
3861 ········/// Remove all unused entries from the cache.
3862 ········/// </summary>
3863 ········public void CleanupCache()
3864 ········{
3865 ············GC.Collect(GC.MaxGeneration);
3866 ············GC.WaitForPendingFinalizers();
3867 ············cache.Cleanup();
3868 ········}
3869
3870 ········/// <summary>
3871 ········/// Remove all unlocked objects from the cache. Use with care!
3872 ········/// </summary>
3873 ········public void UnloadCache()
3874 ········{
3875 ············cache.Unload();
3876 ········}
3877 #endregion
3878
3879 ········/// <summary>
3880 ········/// Default encryption key for NDO
3881 ········/// </summary>
3882 ········/// <remarks>
3883 ········/// We recommend strongly to use an own encryption key, which can be set with this property.
3884 ········/// </remarks>
3885 ········public virtual byte[] EncryptionKey
3886 ········{
3887 ············get
3888 ············{
3889 ················if (this.encryptionKey == null)
3890 ····················this.encryptionKey = new byte[] { 0x09,0xA2,0x79,0x5C,0x99,0xFF,0xCB,0x8B,0xA3,0x37,0x76,0xC8,0xA6,0x5D,0x6D,0x66,
3891 ······················································0xE2,0x74,0xCF,0xF0,0xF7,0xEA,0xC4,0x82,0x1E,0xD5,0x19,0x4C,0x5A,0xB4,0x89,0x4D };
3892 ················return this.encryptionKey;
3893 ············}
3894 ············set { this.encryptionKey = value; }
3895 ········}
3896
3897 ········/// <summary>
3898 ········/// Hollow mode: If true all objects are made hollow after each transaction.
3899 ········/// </summary>
3900 ········public virtual bool HollowMode
3901 ········{
3902 ············get { return hollowMode; }
3903 ············set { hollowMode = value; }
3904 ········}
3905
3906 ········internal TypeManager TypeManager
3907 ········{
3908 ············get { return typeManager; }
3909 ········}
3910
3911 ········/// <summary>
3912 ········/// Sets or gets transaction mode. Uses TransactionMode enum.
3913 ········/// </summary>
3914 ········/// <remarks>
3915 ········/// Set this value before you start any transactions.
3916 ········/// </remarks>
3917 ········public TransactionMode TransactionMode
3918 ········{
3919 ············get { return TransactionScope.TransactionMode; }
3920 ············set { TransactionScope.TransactionMode = value; }
3921 ········}
3922
3923 ········/// <summary>
3924 ········/// Sets or gets the Isolation Level.
3925 ········/// </summary>
3926 ········/// <remarks>
3927 ········/// Set this value before you start any transactions.
3928 ········/// </remarks>
3929 ········public IsolationLevel IsolationLevel
3930 ········{
3931 ············get { return TransactionScope.IsolationLevel; }
3932 ············set { TransactionScope.IsolationLevel = value; }
3933 ········}
3934
3935 ········internal class MappingTableEntry
3936 ········{
3937 ············private IPersistenceCapable parentObject;
3938 ············private IPersistenceCapable relatedObject;
3939 ············private Relation relation;
3940 ············private bool deleteEntry;
3941 ············
3942 ············public MappingTableEntry(IPersistenceCapable pc, IPersistenceCapable relObj, Relation r) : this(pc, relObj, r, false)
3943 ············{
3944 ············}
3945 ············
3946 ············public MappingTableEntry(IPersistenceCapable pc, IPersistenceCapable relObj, Relation r, bool deleteEntry)
3947 ············{
3948 ················parentObject = pc;
3949 ················relatedObject = relObj;
3950 ················relation = r;
3951 ················this.deleteEntry = deleteEntry;
3952 ············}
3953
3954 ············public bool DeleteEntry
3955 ············{
3956 ················get
3957 ················{
3958 ····················return deleteEntry;
3959 ················}
3960 ············}
3961
3962 ············public IPersistenceCapable ParentObject
3963 ············{
3964 ················get
3965 ················{
3966 ····················return parentObject;
3967 ················}
3968 ············}
3969
3970 ············public IPersistenceCapable RelatedObject
3971 ············{
3972 ················get
3973 ················{
3974 ····················return relatedObject;
3975 ················}
3976 ············}
3977
3978 ············public Relation Relation
3979 ············{
3980 ················get
3981 ················{
3982 ····················return relation;
3983 ················}
3984 ············}
3985 ········}
3986
3987 ········/// <summary>
3988 ········/// Get a DataRow representing the given object.
3989 ········/// </summary>
3990 ········/// <param name="o"></param>
3991 ········/// <returns></returns>
3992 ········public DataRow GetClonedDataRow( object o )
3993 ········{
3994 ············IPersistenceCapable pc = CheckPc( o );
3995
3996 ············if (pc.NDOObjectState == NDOObjectState.Deleted || pc.NDOObjectState == NDOObjectState.Transient)
3997 ················throw new Exception( "GetDataRow: State of the object must not be Deleted or Transient." );
3998
3999 ············DataRow row = cache.GetDataRow( pc );
4000 ············DataTable newTable = row.Table.Clone();
4001 ············newTable.ImportRow( row );
4002 ············row = newTable.Rows[0];
4003
4004 ············Class cls = mappings.FindClass(o.GetType());
4005 ············WriteObject( pc, row, cls.ColumnNames );
4006 ············WriteForeignKeysToRow( pc, row );
4007
4008 ············return row;
4009 ········}
4010
4011 ········/// <summary>
4012 ········/// Gets an object, which shows all changes applied to the given object.
4013 ········/// This function can be used to build an audit system.
4014 ········/// </summary>
4015 ········/// <param name="o"></param>
4016 ········/// <returns>An ExpandoObject</returns>
4017 ········public ChangeLog GetChangeSet( object o )
4018 ········{
4019 ············var changeLog = new ChangeLog(this);
4020 ············changeLog.Initialize( o );
4021 ············return changeLog;
4022 ········}
4023
4024 ········/// <summary>
4025 ········/// Outputs a revision number representing the assembly version.
4026 ········/// </summary>
4027 ········/// <remarks>This can be used for debugging purposes</remarks>
4028 ········public int Revision
4029 ········{
4030 ············get
4031 ············{
4032 ················Version v = new AssemblyName( GetType().Assembly.FullName ).Version;
4033 ················string vstring = String.Format( "{0}{1:D2}{2}{3:D2}", v.Major, v.Minor, v.Build, v.MinorRevision );
4034 ················return int.Parse( vstring );
4035 ············}
4036 ········}
4037 ····}
4038 }
4039
New Commit (cf9949d)
1 //
2 // Copyright (c) 2002-2024 Mirko Matytschak
3 // (www.netdataobjects.de)
4 //
5 // Author: Mirko Matytschak
6 //
7 // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
8 // documentation files (the "Software"), to deal in the Software without restriction, including without limitation
9 // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
10 // Software, and to permit persons to whom the Software is furnished to do so, subject to the following
11 // conditions:
12
13 // The above copyright notice and this permission notice shall be included in all copies or substantial portions
14 // of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
17 // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
19 // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 // DEALINGS IN THE SOFTWARE.
21
22
23 using System;
24 using System.Text;
25 using System.IO;
26 using System.Collections;
27 using System.Collections.Generic;
28 using System.Data;
29 using System.Diagnostics;
30 using System.Reflection;
31 using System.Text.RegularExpressions;
32 using System.Linq;
33 using System.Xml.Linq;
34 using System.Data.Common;
35 using System.Runtime.CompilerServices;
36 using System.Threading;
37 using System.Threading.Tasks;
38
39 using NDO.Mapping;
40 using NDOInterfaces;
41 using NDO.ShortId;
42 using System.Globalization;
43 using NDO.Linq;
44 using NDO.Query;
45 using NDO.ChangeLogging;
46 using Microsoft.Extensions.DependencyInjection;
47 using Microsoft.Extensions.Logging;
48
49 namespace NDO
50 {
51 ····/// <summary>
52 ····/// Delegate type of an handler, which can be registered by the CollisionEvent of the PersistenceManager.
53 ····/// <see cref="NDO.PersistenceManager.CollisionEvent"/>
54 ····/// </summary>
55 ····public delegate void CollisionHandler(object o);
56 ····/// <summary>
57 ····/// Delegate type of an handler, which can be registered by the IdGenerationEvent event of the PersistenceManager.
58 ····/// <see cref="NDO.PersistenceManagerBase.IdGenerationEvent"/>
59 ····/// </summary>
60 ····public delegate void IdGenerationHandler(Type t, ObjectId oid);
61 ····/// <summary>
62 ····/// Delegate type of an handler, which can be registered by the OnSaving event of the PersistenceManager.
63 ····/// </summary>
64 ····public delegate void OnSavingHandler(ICollection l);
65 ····/// <summary>
66 ····/// Delegate type for the OnSavedEvent.
67 ····/// </summary>
68 ····/// <param name="auditSet"></param>
69 ····public delegate void OnSavedHandler(AuditSet auditSet);
70
71 ····/// <summary>
72 ····/// Delegate type of an handler, which can be registered by the ObjectNotPresentEvent of the PersistenceManager. The event will be called, if LoadData doesn't find an object with the given oid.
73 ····/// </summary>
74 ····/// <param name="pc"></param>
75 ····/// <returns>A boolean value which determines, if the handler could solve the situation.</returns>
76 ····/// <remarks>If the handler returns false, NDO will throw an exception.</remarks>
77 ····public delegate bool ObjectNotPresentHandler( IPersistenceCapable pc );
78
79 ····/// <summary>
80 ····/// Standard implementation of the IPersistenceManager interface. Provides transaction like manipulation of data sets.
81 ····/// This is the main class you'll work with in your application code. For more information see the topic "Persistence Manager" in the NDO Documentation.
82 ····/// </summary>
83 ····public class PersistenceManager : PersistenceManagerBase, IPersistenceManager
84 ····{········
85 ········private bool hollowMode = false;
86 ········private Dictionary<Relation, IMappingTableHandler> mappingHandler = new Dictionary<Relation,IMappingTableHandler>(); // currently used handlers
87
88 ········private Hashtable currentRelations = new Hashtable(); // Contains names of current bidirectional relations
89 ········private ObjectLock removeLock = new ObjectLock();
90 ········private ObjectLock addLock = new ObjectLock();
91 ········private ArrayList createdDirectObjects = new ArrayList(); // List of newly created objects that need to be stored twice to update foreign keys.
92 ········// List of created objects that use mapping table and need to be stored in mapping table
93 ········// after they have been stored to the database to update foreign keys.
94 ········private ArrayList createdMappingTableObjects = new ArrayList();··
95 ········private TypeManager typeManager;
96 ········internal bool DeferredMode { get; private set; }
97 ········private INDOTransactionScope transactionScope;
98 ········internal INDOTransactionScope TransactionScope => transactionScope ?? (transactionScope = ServiceProvider.GetRequiredService<INDOTransactionScope>().Initialize(this));········
99
100 ········private OpenConnectionListener openConnectionListener;
101
102 ········/// <summary>
103 ········/// Register a listener to this event if you work in concurrent scenarios and you use TimeStamps.
104 ········/// If a collision occurs, this event gets fired and gives the opportunity to handle the situation.
105 ········/// </summary>
106 ········public event CollisionHandler CollisionEvent;
107
108 ········/// <summary>
109 ········/// Register a listener to this event to handle situations where LoadData doesn't find an object.
110 ········/// The listener can determine, whether an exception should be thrown, if the situation occurs.
111 ········/// </summary>
112 ········public event ObjectNotPresentHandler ObjectNotPresentEvent;
113
114 ········/// <summary>
115 ········/// Register a listener to this event, if you want to be notified about the end
116 ········/// of a transaction. The listener gets a ICollection of all objects, which have been changed
117 ········/// during the transaction and are to be saved or deleted.
118 ········/// </summary>
119 ········public event OnSavingHandler OnSavingEvent;
120 ········/// <summary>
121 ········/// This event is fired at the very end of the Save() method. It provides lists of the added, changed, and deleted objects.
122 ········/// </summary>
123 ········public event OnSavedHandler OnSavedEvent;
124 ········
125 ········private const string hollowMarker = "Hollow";
126 ········private byte[] encryptionKey;
127 ········private List<RelationChangeRecord> relationChanges = new List<RelationChangeRecord>();
128 ········private bool isClosing = false;
129
130 ········/// <summary>
131 ········/// Gets a list of structures which represent relation changes, i.e. additions and removals
132 ········/// </summary>
133 ········protected internal List<RelationChangeRecord> RelationChanges
134 ········{
135 ············get { return this.relationChanges; }
136 ········}
137
138 ········/// <summary>
139 ········/// Initializes a new PersistenceManager instance.
140 ········/// </summary>
141 ········/// <param name="mappingFileName"></param>
142 ········protected override void Init(string mappingFileName)
143 ········{
144 ············try
145 ············{
146 ················base.Init(mappingFileName);
147 ············}
148 ············catch (Exception ex)
149 ············{
150 ················if (ex is NDOException)
151 ····················throw;
152 ················throw new NDOException(30, "Persistence manager initialization error: " + ex.ToString());
153 ············}
154
155 ········}
156
157 ········/// <summary>
158 ········/// Initializes the persistence manager
159 ········/// </summary>
160 ········/// <remarks>
161 ········/// Note: This is the method, which will be called from all different ways to instantiate a PersistenceManagerBase.
162 ········/// </remarks>
163 ········/// <param name="mapping"></param>
164 ········internal override void Init( Mappings mapping )
165 ········{
166 ············base.Init( mapping );
167
168 ············string dir = Path.GetDirectoryName( mapping.FileName );
169
170 ············string typesFile = Path.Combine( dir, "NDOTypes.xml" );
171 ············typeManager = new TypeManager( typesFile, this.mappings );
172
173 ············sm = new StateManager( this );
174
175 ············InitClasses();
176 ········}
177
178
179 ········/// <summary>
180 ········/// Standard Constructor.
181 ········/// </summary>
182 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
183 ········/// <remarks>
184 ········/// Searches for a mapping file in the application directory.
185 ········/// The constructor tries to find a file with the same name as
186 ········/// the assembly, but with the extension .ndo.xml. If the file is not found the constructor tries to find a
187 ········/// file called AssemblyName.ndo.mapping in the application directory.
188 ········/// </remarks>
189 ········public PersistenceManager( IServiceProvider scopedServiceProvider = null ) : base( scopedServiceProvider )
190 ········{
191 ········}
192
193 ········/// <summary>
194 ········/// Loads the mapping file from the specified location. This allows to use
195 ········/// different mapping files with different classes mapped in it.
196 ········/// </summary>
197 ········/// <param name="mappingFile">Path to the mapping file.</param>
198 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
199 ········/// <remarks>Only the Professional and Enterprise
200 ········/// Editions can handle more than one mapping file.</remarks>
201 ········public PersistenceManager(string mappingFile, IServiceProvider scopedServiceProvider = null) : base (mappingFile, scopedServiceProvider)
202 ········{
203 ········}
204
205 ········/// <summary>
206 ········/// Constructs a PersistenceManager and reuses a cached NDOMapping.
207 ········/// </summary>
208 ········/// <param name="mapping">The cached mapping object</param>
209 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
210 ········public PersistenceManager(NDOMapping mapping, IServiceProvider scopedServiceProvider = null) : base (mapping, scopedServiceProvider)
211 ········{
212 ········}
213
214 ········#region Object Container Stuff
215 ········/// <summary>
216 ········/// Gets a container of all loaded objects and tries to load all child objects,
217 ········/// which are reachable through composite relations.
218 ········/// </summary>
219 ········/// <returns>An ObjectContainer object.</returns>
220 ········/// <remarks>
221 ········/// It is not recommended, to transfer objects with a state other than Hollow,
222 ········/// Persistent, or Transient.
223 ········/// The transfer format is binary.
224 ········/// </remarks>
225 ········public ObjectContainer GetObjectContainer()
226 ········{
227 ············IList l = this.cache.AllObjects;
228 ············foreach(IPersistenceCapable pc in l)
229 ············{
230 ················if (pc.NDOObjectState == NDOObjectState.PersistentDirty)
231 ················{
232 ····················if (Logger != null)
233 ························Logger.LogWarning( "Call to GetObjectContainer returns changed objects." );
234 ················}
235 ············}
236
237 ············ObjectContainer oc = new ObjectContainer();
238 ············oc.AddList(l);
239 ············return oc;
240 ········}
241
242 ········/// <summary>
243 ········/// Returns a container of all objects provided in the objects list and searches for
244 ········/// child objects according to the serFlags.
245 ········/// </summary>
246 ········/// <param name="objects">The list of the root objects to add to the container.</param>
247 ········/// <returns>An ObjectContainer object.</returns>
248 ········/// <remarks>
249 ········/// It is not recommended, to transfer objects with a state other than Hollow,
250 ········/// Persistent, or Transient.
251 ········/// </remarks>
252 ········public ObjectContainer GetObjectContainer(IList objects)
253 ········{
254 ············foreach(object o in objects)
255 ············{
256 ················CheckPc(o);
257 ················IPersistenceCapable pc = o as IPersistenceCapable;
258 ················if (pc.NDOObjectState == NDOObjectState.Hollow)
259 ····················LoadData(pc);
260 ············}
261 ············ObjectContainer oc = new ObjectContainer();
262 ············oc.AddList(objects);
263 ············return oc;
264 ········}
265
266
267 ········/// <summary>
268 ········/// Returns a container containing the provided object
269 ········/// and tries to load all child objects
270 ········/// reachable through composite relations.
271 ········/// </summary>
272 ········/// <param name="obj">The object to be added to the container.</param>
273 ········/// <returns>An ObjectContainer object.</returns>
274 ········/// <remarks>
275 ········/// It is not recommended, to transfer objects with a state other than Hollow,
276 ········/// Persistent, or Transient.
277 ········/// The transfer format is binary.
278 ········/// </remarks>
279 ········public ObjectContainer GetObjectContainer(Object obj)
280 ········{
281 ············CheckPc(obj);
282 ············if (((IPersistenceCapable)obj).NDOObjectState == NDOObjectState.Hollow)
283 ················LoadData(obj);
284 ············ObjectContainer oc = new ObjectContainer();
285 ············oc.AddObject(obj);
286 ············return oc;
287 ········}
288
289 ········/// <summary>
290 ········/// Merges an object container to the active objects in the pm. All changes and the state
291 ········/// of the objects will be taken over by the pm.
292 ········/// </summary>
293 ········/// <remarks>
294 ········/// The parameter can be either an ObjectContainer or a ChangeSetContainer.
295 ········/// The flag MarkAsTransient can be used to perform a kind
296 ········/// of object based replication using the ObjectContainer class.
297 ········/// Objects, which are persistent at one machine, can be transfered
298 ········/// to a second machine and treated by the receiving PersistenceManager like a newly created
299 ········/// object. The receiving PersistenceManager will use MakePersistent to store the whole
300 ········/// transient object tree.
301 ········/// There is one difference to freshly created objects: If an object id exists, it will be
302 ········/// serialized. If the NDOOidType-Attribute is valid for the given class, the transfered
303 ········/// oids will be reused by the receiving PersistenceManager.
304 ········/// </remarks>
305 ········/// <param name="ocb">The object container to be merged.</param>
306 ········public void MergeObjectContainer(ObjectContainerBase ocb)
307 ········{
308 ············ChangeSetContainer csc = ocb as ChangeSetContainer;
309 ············if (csc != null)
310 ············{
311 ················MergeChangeSet(csc);
312 ················return;
313 ············}
314 ············ObjectContainer oc = ocb as ObjectContainer;
315 ············if (oc != null)
316 ············{
317 ················InternalMergeObjectContainer(oc);
318 ················return;
319 ············}
320 ············throw new NDOException(42, "Wrong argument type: MergeObjectContainer expects either an ObjectContainer or a ChangeSetContainer object as parameter.");
321 ········}
322
323
324 ········void InternalMergeObjectContainer(ObjectContainer oc)
325 ········{
326 ············// TODO: Check, if other states are useful. Find use scenarios.
327 ············foreach(IPersistenceCapable pc in oc.RootObjects)
328 ············{
329 ················if (pc.NDOObjectState == NDOObjectState.Transient)
330 ····················MakePersistent(pc);
331 ············}
332 ············foreach(IPersistenceCapable pc in oc.RootObjects)
333 ············{
334 ················new OnlineMergeIterator(this.sm, this.cache).Iterate(pc);
335 ············}
336 ········}
337
338 ········void MergeChangeSet(ChangeSetContainer cs)
339 ········{
340 ············foreach(IPersistenceCapable pc in cs.AddedObjects)
341 ············{
342 ················InternalMakePersistent(pc, false);
343 ············}
344 ············foreach(ObjectId oid in cs.DeletedObjects)
345 ············{
346 ················IPersistenceCapable pc2 = FindObject(oid);
347 ················Delete(pc2);
348 ············}
349 ············foreach(IPersistenceCapable pc in cs.ChangedObjects)
350 ············{
351 ················IPersistenceCapable pc2 = FindObject(pc.NDOObjectId);
352 ················Class pcClass = GetClass(pc);
353 ················// Make sure, the object is loaded.
354 ················if (pc2.NDOObjectState == NDOObjectState.Hollow)
355 ····················LoadData(pc2);
356 ················MarkDirty( pc2 );··// This locks the object and generates a LockEntry, which contains a row
357 ················var entry = cache.LockedObjects.FirstOrDefault( e => e.pc.NDOObjectId == pc.NDOObjectId );
358 ················DataRow row = entry.row;
359 ················pc.NDOWrite(row, pcClass.ColumnNames, 0);
360 ················pc2.NDORead(row, pcClass.ColumnNames, 0);
361 ············}
362 ············foreach(RelationChangeRecord rcr in cs.RelationChanges)
363 ············{
364 ················IPersistenceCapable parent = FindObject(rcr.Parent.NDOObjectId);
365 ················IPersistenceCapable child = FindObject(rcr.Child.NDOObjectId);
366 ················Class pcClass = GetClass(parent);
367 ················Relation r = pcClass.FindRelation(rcr.RelationName);
368 ················if (!parent.NDOLoadState.RelationLoadState[r.Ordinal])
369 ····················LoadRelation(parent, r, true);
370 ················if (rcr.IsAdded)
371 ················{
372 ····················InternalAddRelatedObject(parent, r, child, true);
373 ····················if (r.Multiplicity == RelationMultiplicity.Element)
374 ····················{
375 ························mappings.SetRelationField(parent, r.FieldName, child);
376 ····················}
377 ····················else
378 ····················{
379 ························IList l = mappings.GetRelationContainer(parent, r);
380 ························l.Add(child);
381 ····················}
382 ················}
383 ················else
384 ················{
385 ····················RemoveRelatedObject(parent, r.FieldName, child);
386 ····················if (r.Multiplicity == RelationMultiplicity.Element)
387 ····················{
388 ························mappings.SetRelationField(parent, r.FieldName, null);
389 ····················}
390 ····················else
391 ····················{
392 ························IList l = mappings.GetRelationContainer(parent, r);
393 ························try
394 ························{
395 ····························ObjectListManipulator.Remove(l, child);
396 ························}
397 ························catch
398 ························{
399 ····························throw new NDOException(50, "Error while merging a ChangeSetContainer: Child " + child.NDOObjectId.ToString() + " doesn't exist in relation " + parent.GetType().FullName + '.' + r.FieldName);
400 ························}
401 ····················}
402 ················}
403 ············}
404
405 ········}
406 ········#endregion
407
408 ········#region Implementation of IPersistenceManager
409
410 ········// Complete documentation can be found in IPersistenceManager
411
412
413 ········void WriteDependentForeignKeysToRow(IPersistenceCapable pc, Class cl, DataRow row)
414 ········{
415 ············if (!cl.Oid.IsDependent)
416 ················return;
417 ············WriteForeignKeysToRow(pc, row);
418 ········}
419
420 ········void InternalMakePersistent(IPersistenceCapable pc, bool checkRelations)
421 ········{
422 ············// Object is now under control of the state manager
423 ············pc.NDOStateManager = sm;
424
425 ············Type pcType = pc.GetType();
426 ············Class pcClass = GetClass(pc);
427
428 ············// Create new object
429 ············DataTable dt = GetTable(pcType);
430 ············DataRow row = dt.NewRow();·· // In case of autoincremented oid, the row has a temporary oid value
431
432 ············// In case of a Guid oid the value will be computed now.
433 ············foreach (OidColumn oidColumn in pcClass.Oid.OidColumns)
434 ············{
435 ················if (oidColumn.SystemType == typeof(Guid) && oidColumn.FieldName == null && oidColumn.RelationName ==null)
436 ················{
437 ····················if (dt.Columns[oidColumn.Name].DataType == typeof(string))
438 ························row[oidColumn.Name] = Guid.NewGuid().ToString();
439 ····················else
440 ························row[oidColumn.Name] = Guid.NewGuid();
441 ················}
442 ············}
443
444 ············WriteObject(pc, row, pcClass.ColumnNames, 0); // save current state in DS
445
446 ············// If the object is merged from an ObjectContainer, the id should be reused,
447 ············// if the id is client generated (not Autoincremented).
448 ············// In every other case, the oid is set to null, to force generating a new oid.
449 ············bool fireIdGeneration = (Object)pc.NDOObjectId == null;
450 ············if ((object)pc.NDOObjectId != null)
451 ············{
452 ················bool hasAutoincrement = false;
453 ················foreach (OidColumn oidColumn in pcClass.Oid.OidColumns)
454 ················{
455 ····················if (oidColumn.AutoIncremented)
456 ····················{
457 ························hasAutoincrement = true;
458 ························break;
459 ····················}
460 ················}
461 ················if (hasAutoincrement) // can't store existing id
462 ················{
463 ····················pc.NDOObjectId = null;
464 ····················fireIdGeneration = true;
465 ················}
466 ············}
467
468 ············// In case of a dependent class the oid has to be read from the fields according to the relations
469 ············WriteDependentForeignKeysToRow(pc, pcClass, row);
470
471 ············if ((object)pc.NDOObjectId == null)
472 ············{
473 ················pc.NDOObjectId = ObjectIdFactory.NewObjectId(pcType, pcClass, row, this.typeManager);
474 ············}
475
476 ············if (!pcClass.Oid.IsDependent) // Dependent keys can't be filled with user defined data
477 ············{
478 ················if (fireIdGeneration)
479 ····················FireIdGenerationEvent(pcType, pc.NDOObjectId);
480 ················// At this place the oid might have been
481 ················// - deserialized (MergeObjectContainer)
482 ················// - created using NewObjectId
483 ················// - defined by the IdGenerationEvent
484
485 ················// At this point we have a valid oid.
486 ················// If the object has a field mapped to the oid we have
487 ················// to write back the oid to the field
488 ················int i = 0;
489 ················new OidColumnIterator(pcClass).Iterate(delegate(OidColumn oidColumn, bool isLastElement)
490 ················{
491 ····················if (oidColumn.FieldName != null)
492 ····················{
493 ························FieldInfo fi = new BaseClassReflector(pcType).GetField(oidColumn.FieldName, BindingFlags.NonPublic | BindingFlags.Instance);
494 ························fi.SetValue(pc, pc.NDOObjectId.Id[i]);
495 ····················}
496 ····················i++;
497 ················});
498
499
500
501 ················// Now write back the data into the row
502 ················pc.NDOObjectId.Id.ToRow(pcClass, row);
503 ············}
504
505 ············
506 ············ReadLostForeignKeysFromRow(pcClass, pc, row);··// they contain all DBNull at the moment
507 ············dt.Rows.Add(row);
508
509 ············cache.Register(pc);
510
511 ············// new object that has never been written to the DS
512 ············pc.NDOObjectState = NDOObjectState.Created;
513 ············// Mark all Relations as loaded
514 ············SetRelationState(pc);
515
516 ············if (checkRelations)
517 ············{
518 ················// Handle related objects:
519 ················foreach(Relation r in pcClass.Relations)
520 ················{
521 ····················if (r.Multiplicity == RelationMultiplicity.Element)
522 ····················{
523 ························IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
524 ························if(child != null)
525 ························{
526 ····························AddRelatedObject(pc, r, child);
527 ························}
528 ····················}
529 ····················else
530 ····················{
531 ························IList list = mappings.GetRelationContainer(pc, r);
532 ························if(list != null)
533 ························{
534 ····························foreach(IPersistenceCapable relObj in list)
535 ····························{
536 ································if (relObj != null)
537 ····································AddRelatedObject(pc, r, relObj);
538 ····························}
539 ························}
540 ····················}
541 ················}
542 ············}
543
544 ············var relations··= CollectRelationStates(pc);
545 ············cache.Lock(pc, row, relations);
546 ········}
547
548
549 ········/// <summary>
550 ········/// Make an object persistent.
551 ········/// </summary>
552 ········/// <param name="o">the transient object that should be made persistent</param>
553 ········public void MakePersistent(object o)
554 ········{
555 ············if (IsClosed)
556 ················throw new ObjectDisposedException( GetType().Name );····
557
558 ············IPersistenceCapable pc = CheckPc(o);
559
560 ············//Debug.WriteLine("MakePersistent: " + pc.GetType().Name);
561 ············//Debug.Indent();
562
563 ············if (pc.NDOObjectState != NDOObjectState.Transient)
564 ················throw new NDOException(54, "MakePersistent: Object is already persistent: " + pc.NDOObjectId.Dump());
565
566 ············InternalMakePersistent(pc, true);
567
568 ········}
569
570
571
572 ········//········/// <summary>
573 ········//········/// Checks, if an object has a valid id, which was created by the database
574 ········//········/// </summary>
575 ········//········/// <param name="pc"></param>
576 ········//········/// <returns></returns>
577 ········//········private bool HasValidId(IPersistenceCapable pc)
578 ········//········{
579 ········//············if (this.IdGenerationEvent != null)
580 ········//················return true;
581 ········//············return (pc.NDOObjectState != NDOObjectState.Created && pc.NDOObjectState != NDOObjectState.Transient);
582 ········//········}
583
584
585 ········private void CreateAddedObjectRow(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj, bool makeRelObjPersistent)
586 ········{
587 ············// for a "1:n"-Relation w/o mapping table, we add the foreign key here.
588 ············if(r.HasSubclasses)
589 ············{
590 ················// we don't support 1:n with foreign fields in subclasses because we would have to
591 ················// search for objects in all subclasses! Instead use a mapping table.
592 ················// throw new NDOException(55, "1:n Relations with subclasses must use a mapping table: " + r.FieldName);
593 ················Debug.WriteLine("CreateAddedObjectRow: Polymorphic 1:n-relation " + r.Parent.FullName + "." + r.FieldName + " w/o mapping table");
594 ············}
595
596 ············if (!makeRelObjPersistent)
597 ················MarkDirty(relObj);
598 ············// Because we just marked the object as dirty, we know it's in the cache, so we don't supply the idColumn
599 ············DataRow relObjRow = this.cache.GetDataRow(relObj);
600
601 ············if (relObjRow == null)
602 ················throw new InternalException(537, "CreateAddedObjectRow: relObjRow == null");
603
604 ············pc.NDOObjectId.Id.ToForeignKey(r, relObjRow);
605
606 ············if (relObj.NDOLoadState.LostRowInfo == null)
607 ············{
608 ················ReadLostForeignKeysFromRow(GetClass(relObj), relObj, relObjRow);
609 ············}
610 ············else
611 ············{
612 ················relObj.NDOLoadState.ReplaceRowInfos(r, pc.NDOObjectId.Id);
613 ············}
614 ········}
615
616 ········private void PatchForeignRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
617 ········{
618 ············switch(relObj.NDOObjectState)
619 ············{
620 ················case NDOObjectState.Persistent:
621 ····················MarkDirty(relObj);
622 ····················break;
623 ················case NDOObjectState.Hollow:
624 ····················LoadData(relObj);
625 ····················MarkDirty(relObj);
626 ····················break;
627 ············}
628
629 ············if(r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
630 ············{
631 ················IPersistenceCapable newpc;
632 ················if((newpc = (IPersistenceCapable) mappings.GetRelationField(relObj, r.ForeignRelation.FieldName)) != null)
633 ················{
634 ····················if (newpc != pc)
635 ························throw new NDOException(56, "Object is already part of another relation: " + relObj.NDOObjectId.Dump());
636 ················}
637 ················else
638 ················{
639 ····················mappings.SetRelationField(relObj, r.ForeignRelation.FieldName, pc);
640 ················}
641 ············}
642 ············else
643 ············{
644 ················if (!relObj.NDOGetLoadState(r.ForeignRelation.Ordinal))
645 ····················LoadRelation(relObj, r.ForeignRelation, true);
646 ················IList l = mappings.GetRelationContainer(relObj, r.ForeignRelation);
647 ················if(l == null)
648 ················{
649 ····················try
650 ····················{
651 ························l = mappings.CreateRelationContainer(relObj, r.ForeignRelation);
652 ····················}
653 ····················catch
654 ····················{
655 ························throw new NDOException(57, "Can't construct IList member " + relObj.GetType().FullName + "." + r.FieldName + ". Initialize the field in the default class constructor.");
656 ····················}
657 ····················mappings.SetRelationContainer(relObj, r.ForeignRelation, l);
658 ················}
659 ················// Hack: Es sollte erst gar nicht zu diesem Aufruf kommen.
660 ················// Zus�tzlicher Funktions-Parameter addObjectToList oder so.
661 ················if (!ObjectListManipulator.Contains(l, pc))
662 ····················l.Add(pc);
663 ············}
664 ············//AddRelatedObject(relObj, r.ForeignRelation, pc);
665 ········}
666
667
668 ········/// <summary>
669 ········/// Add a related object to the specified object.
670 ········/// </summary>
671 ········/// <param name="pc">the parent object</param>
672 ········/// <param name="fieldName">the field name of the relation</param>
673 ········/// <param name="relObj">the related object that should be added</param>
674 ········internal virtual void AddRelatedObject(IPersistenceCapable pc, string fieldName, IPersistenceCapable relObj)
675 ········{
676 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient);
677 ············Relation r = mappings.FindRelation(pc, fieldName);
678 ············AddRelatedObject(pc, r, relObj);
679 ········}
680
681 ········/// <summary>
682 ········/// Core functionality to add an object to a relation container or relation field.
683 ········/// </summary>
684 ········/// <param name="pc"></param>
685 ········/// <param name="r"></param>
686 ········/// <param name="relObj"></param>
687 ········/// <param name="isMerging"></param>
688 ········protected virtual void InternalAddRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj, bool isMerging)
689 ········{
690 ············
691 ············// avoid recursion
692 ············if (!addLock.GetLock(relObj))
693 ················return;
694
695 ············try
696 ············{
697 ················//TODO: We need a relation management, which is independent of
698 ················//the state management of an object. Currently the relation
699 ················//lists or elements are cached for restore, if an object is marked dirty.
700 ················//Thus we have to mark dirty our parent object in any case at the moment.
701 ················MarkDirty(pc);
702
703 ················//We should mark pc as dirty if we have a 1:1 w/o mapping table
704 ················//We should mark relObj as dirty if we have a 1:n w/o mapping table
705 ················//The latter happens in CreateAddedObjectRow
706
707 ················Class relClass = GetClass(relObj);
708
709 ················if (r.Multiplicity == RelationMultiplicity.Element
710 ····················&& r.HasSubclasses
711 ····················&& r.MappingTable == null················
712 ····················&& !this.HasOwnerCreatedIds
713 ····················&& GetClass(pc).Oid.HasAutoincrementedColumn
714 ····················&& !relClass.HasGuidOid)
715 ················{
716 ····················if (pc.NDOObjectState == NDOObjectState.Created && (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient ))
717 ························throw new NDOException(61, "Can't assign object of type " + relObj + " to relation " + pc.GetType().FullName + "." + r.FieldName + ". The parent object must be saved first to obtain the Id (for example with pm.Save(true)). As an alternative you can use client generated Id's or a mapping table.");
718 ····················if (r.Composition)
719 ························throw new NDOException(62, "Can't assign object of type " + relObj + " to relation " + pc.GetType().FullName + "." + r.FieldName + ". Can't handle a polymorphic composite relation with cardinality 1 with autonumbered id's. Use a mapping table or client generated id's.");
720 ····················if (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient)
721 ························throw new NDOException(63, "Can't assign an object of type " + relObj + " to relation " + pc.GetType().FullName + "." + r.FieldName + ". The child object must be saved first to obtain the Id (for example with pm.Save(true)). As an alternative you can use client generated Id's or a mapping table." );
722 ················}
723
724 ················bool isDependent = relClass.Oid.IsDependent;
725
726 ················if (r.Multiplicity == RelationMultiplicity.Element && isDependent)
727 ····················throw new NDOException(28, "Relations to intermediate classes must have RelationMultiplicity.List.");
728
729 ················// Need to patch pc into the relation relObj->pc, because
730 ················// the oid is built on base of this information
731 ················if (isDependent)
732 ················{
733 ····················CheckDependentKeyPreconditions(pc, r, relObj, relClass);
734 ················}
735
736 ················if (r.Composition || isDependent)
737 ················{
738 ····················if (!isMerging || relObj.NDOObjectState == NDOObjectState.Transient)
739 ························MakePersistent(relObj);
740 ················}
741
742 ················if(r.MappingTable == null)
743 ················{
744 ····················if (r.Bidirectional)
745 ····················{
746 ························// This object hasn't been saved yet, so the key is wrong.
747 ························// Therefore, the child must be written twice to update the foreign key.
748 #if trace
749 ························System.Text.StringBuilder sb = new System.Text.StringBuilder();
750 ························if (r.Multiplicity == RelationMultiplicity.Element)
751 ····························sb.Append("1");
752 ························else
753 ····························sb.Append("n");
754 ························sb.Append(":");
755 ························if (r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
756 ····························sb.Append("1");
757 ························else
758 ····························sb.Append("n");
759 ························sb.Append ("OwnCreatedOther");
760 ························sb.Append(relObj.NDOObjectState.ToString());
761 ························sb.Append(' ');
762
763 ························sb.Append(types[0].ToString());
764 ························sb.Append(' ');
765 ························sb.Append(types[1].ToString());
766 ························Debug.WriteLine(sb.ToString());
767 #endif
768 ························//························if (r.Multiplicity == RelationMultiplicity.Element
769 ························//····························&& r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
770 ························//························{
771 ························// Element means:
772 ························// pc is keyholder
773 ························// -> relObj is saved first
774 ························// -> UpdateOrder(pc) > UpdateOrder(relObj)
775 ························// Both are Created - use type sort order
776 ························if (pc.NDOObjectState == NDOObjectState.Created && (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient)
777 ····························&& GetClass(pc).Oid.HasAutoincrementedColumn && GetClass(relObj).Oid.HasAutoincrementedColumn)
778 ························{
779 ····························if (mappings.GetUpdateOrder(pc.GetType())
780 ································< mappings.GetUpdateOrder(relObj.GetType()))
781 ································createdDirectObjects.Add(pc);
782 ····························else
783 ································createdDirectObjects.Add( relObj );
784 ························}
785 ····················}
786 ····················if (r.Multiplicity == RelationMultiplicity.List)
787 ····················{
788 ························CreateAddedObjectRow(pc, r, relObj, r.Composition);
789 ····················}
790 ················}
791 ················else
792 ················{
793 ····················createdMappingTableObjects.Add(new MappingTableEntry(pc, relObj, r));
794 ················}
795 ················if(r.Bidirectional)
796 ················{
797 ····················if (r.Multiplicity == RelationMultiplicity.List && mappings.GetRelationField(relObj, r.ForeignRelation.FieldName) == null)
798 ····················{
799 ························if ( r.ForeignRelation.Multiplicity == RelationMultiplicity.Element )
800 ····························mappings.SetRelationField(relObj, r.ForeignRelation.FieldName, pc);
801 ····················}
802 ····················else if ( !addLock.IsLocked( pc ) )
803 ····················{
804 ························PatchForeignRelation( pc, r, relObj );
805 ····················}
806 ················}
807
808 ················this.relationChanges.Add( new RelationChangeRecord( pc, relObj, r.FieldName, true ) );
809 ············}
810 ············finally
811 ············{
812 ················addLock.Unlock(relObj);
813 ················//Debug.Unindent();
814 ············}
815 ········}
816
817 ········/// <summary>
818 ········/// Returns an integer value which determines the rank of the given type in the update order list.
819 ········/// </summary>
820 ········/// <param name="t">The type to determine the update order.</param>
821 ········/// <returns>An integer value determining the rank of the given type in the update order list.</returns>
822 ········/// <remarks>
823 ········/// This method is used by NDO for diagnostic purposes. There is no value in using this method in user code.
824 ········/// </remarks>
825 ········public int GetUpdateRank(Type t)
826 ········{
827 ············return mappings.GetUpdateOrder(t);
828 ········}
829
830 ········/// <summary>
831 ········/// Add a related object to the specified object.
832 ········/// </summary>
833 ········/// <param name="pc">the parent object</param>
834 ········/// <param name="r">the relation mapping info</param>
835 ········/// <param name="relObj">the related object that should be added</param>
836 ········protected virtual void AddRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
837 ········{
838 ············//············string idstr;
839 ············//············if (relObj.NDOObjectId == null)
840 ············//················idstr = relObj.GetType().ToString();
841 ············//············else
842 ············//················idstr = relObj.NDOObjectId.Dump();
843 ············//Debug.WriteLine("AddRelatedObject " + pc.NDOObjectId.Dump() + " " + idstr);
844 ············//Debug.Indent();
845
846 ············Class relClass = GetClass(relObj);
847 ············bool isDependent = relClass.Oid.IsDependent;
848
849 ············// Do some checks to guarantee that the assignment is correct
850 ············if(r.Composition)
851 ············{
852 ················if(relObj.NDOObjectState != NDOObjectState.Transient)
853 ················{
854 ····················throw new NDOException(58, "Can only add transient objects in Composite relation " + pc.GetType().FullName + "->" + r.ReferencedTypeName + ".");
855 ················}
856 ············}
857 ············else
858 ············{
859 ················if(relObj.NDOObjectState == NDOObjectState.Transient && !isDependent)
860 ················{
861 ····················throw new NDOException(59, "Can only add persistent objects in Assoziation " + pc.GetType().FullName + "->" + r.ReferencedTypeName + ".");
862 ················}
863 ············}
864
865 ············if(!r.ReferencedType.IsAssignableFrom(relObj.GetType()))
866 ············{
867 ················throw new NDOException(60, "AddRelatedObject: Related object must be assignable to type: " + r.ReferencedTypeName + ". Assigned object was: " + relObj.NDOObjectId.Dump() + " Type = " + relObj.GetType());
868 ············}
869
870 ············InternalAddRelatedObject(pc, r, relObj, false);
871
872 ········}
873
874 ········private void CheckDependentKeyPreconditions(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj, Class relClass)
875 ········{
876 ············// Need to patch pc into the relation relObj->pc, because
877 ············// the oid is built on base of this information
878 ············// The second relation has to be set before adding relObj
879 ············// to the relation list.
880 ············PatchForeignRelation(pc, r, relObj);
881 ············IPersistenceCapable parent;
882 ············foreach (Relation oidRelation in relClass.Oid.Relations)
883 ············{
884 ················parent = (IPersistenceCapable)mappings.GetRelationField(relObj, oidRelation.FieldName);
885 ················if (parent == null)
886 ····················throw new NDOException(41, "'" + relClass.FullName + "." + oidRelation.FieldName + "': One of the defining relations of a dependent class object is null - have a look at the documentation about how to initialize dependent class objects.");
887 ················if (parent.NDOObjectState == NDOObjectState.Transient)
888 ····················throw new NDOException(59, "Can only add persistent objects in Assoziation " + relClass.FullName + "." + oidRelation.FieldName + ". Make the object of type " + parent.GetType().FullName + " persistent.");
889
890 ············}
891 ········}
892
893
894 ········/// <summary>
895 ········/// Remove a related object from the specified object.
896 ········/// </summary>
897 ········/// <param name="pc">the parent object</param>
898 ········/// <param name="fieldName">Field name of the relation</param>
899 ········/// <param name="relObj">the related object that should be removed</param>
900 ········internal virtual void RemoveRelatedObject(IPersistenceCapable pc, string fieldName, IPersistenceCapable relObj)
901 ········{
902 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient);
903 ············Relation r = mappings.FindRelation(pc, fieldName);
904 ············InternalRemoveRelatedObject(pc, r, relObj, true);
905 ········}
906
907 ········/// <summary>
908 ········/// Registers a listener which will be notified, if a new connection is opened.
909 ········/// </summary>
910 ········/// <param name="listener">Delegate of a listener function</param>
911 ········/// <remarks>The listener is called the first time a certain connection is used. A call to Save() resets the connection list so that the listener is called again.</remarks>
912 ········public virtual void RegisterConnectionListener(OpenConnectionListener listener)
913 ········{
914 ············this.openConnectionListener = listener;
915 ········}
916
917 ········internal string OnNewConnection(NDO.Mapping.Connection conn)
918 ········{
919 ············if (openConnectionListener != null)
920 ················return openConnectionListener(conn);
921 ············return conn.Name;
922 ········}
923
924
925 ········/*
926 ········doCommit should be:
927 ········
928 ····················Query····Save····Save(true)
929 ········Optimistic····1········1········0
930 ········Pessimistic····0········1········0
931 ············
932 ········Deferred Mode············
933 ····················Query····Save····Save(true)
934 ········Optimistic····0········1········0
935 ········Pessimistic····0········1········0
936 ········ */
937
938 ········internal void CheckEndTransaction(bool doCommit)
939 ········{
940 ············CheckEndTransactionAsync( doCommit ).ConfigureAwait( false ).GetAwaiter().GetResult();
941 ········}
942
943 ········internal async Task CheckEndTransactionAsync( bool doCommit, CancellationToken cancellationToken = default )
944 ········{
945 ············if (doCommit)
946 ············{
947 ················await TransactionScope.CompleteAsync( cancellationToken ).ConfigureAwait( false );
948 ············}
949 ········}
950
951 ········internal Task CheckTransactionAsync( IPersistenceHandlerBase handler, Type t, CancellationToken cancellationToken = default )
952 ········{
953 ············return CheckTransactionAsync( handler, this.GetClass( t ).Connection, cancellationToken );
954 ········}
955
956 ········int activeOperation;
957 ········readonly AsyncLocal<bool> ownsOperation = new AsyncLocal<bool>();
958
959 ········/// <summary>
960 ········/// Marks the begin of an operation with database access. Detects concurrent usage of the PersistenceManager.
961 ········/// </summary>
962 ········/// <param name="caller">The name of the calling method</param>
963 ········/// <returns>An object, which marks the end of the operation if disposed.</returns>
964 ········/// <remarks>
965 ········/// Nested calls in the same logical flow (e.g. lazy loading in an OnSaving handler) are allowed.
966 ········/// The AsyncLocal flows with the ExecutionContext into all awaited calls, but not back to the caller of an async method.
967 ········/// So two concurrently started tasks don't share the ownership.
968 ········/// </remarks>
969 ········internal OperationGuard EnterOperation( [CallerMemberName] string caller = null )
970 ········{
971 ············if (this.ownsOperation.Value)
972 ················return default;··// Nested call in the same logical flow
973 ············if (Interlocked.CompareExchange( ref this.activeOperation, 1, 0 ) != 0)
974 ················throw new NDOException( 122, $"{caller}: The PersistenceManager is already in use by another operation. A PersistenceManager must not be used concurrently. Await each call before starting the next one." );
975 ············this.ownsOperation.Value = true;
976 ············return new OperationGuard( this );
977 ········}
978
979 ········internal readonly struct OperationGuard : IDisposable
980 ········{
981 ············readonly PersistenceManager pm;
982
983 ············public OperationGuard( PersistenceManager pm )
984 ············{
985 ················this.pm = pm;
986 ············}
987
988 ············public void Dispose()
989 ············{
990 ················if (this.pm == null)
991 ····················return;··// Nested call: nothing to release
992 ················this.pm.ownsOperation.Value = false;
993 ················Volatile.Write( ref this.pm.activeOperation, 0 );
994 ············}
995 ········}
996
997 ········/// <summary>
998 ········/// Each and every database operation has to be preceded by a call to this function.
999 ········/// </summary>
1000 ········internal async Task CheckTransactionAsync( IPersistenceHandlerBase handler, Connection ndoConn, CancellationToken cancellationToken = default )
1001 ········{
1002 ············await TransactionScope.CheckTransactionAsync( cancellationToken ).ConfigureAwait( false );
1003 ············
1004 ············if (handler.Connection == null)
1005 ············{
1006 ················handler.Connection = await TransactionScope.GetConnectionAsync(ndoConn, () =>
1007 ················{
1008 ····················IProvider p = ndoConn.Parent.GetProvider( ndoConn );
1009 ····················string connStr = this.OnNewConnection( ndoConn );
1010 ····················var connection = p.NewConnection( connStr );
1011 ····················if (connection == null)
1012 ························throw new NDOException( 119, $"Can't construct connection for {connStr}. The provider returns null." );
1013 ····················LogIfVerbose( $"Creating a connection object for {ndoConn.DisplayName}" );
1014 ····················return connection;
1015 ················}, cancellationToken ).ConfigureAwait( false );
1016 ············}
1017
1018 ············if (TransactionMode != TransactionMode.None)
1019 ············{
1020 ················handler.Transaction = TransactionScope.GetTransaction( ndoConn.ID );
1021 ············}
1022
1023 ············// There are tests with a handler mock that always returns zero for the Connection property.
1024 ············if (handler.Connection != null && handler.Connection.State != ConnectionState.Open)
1025 ············{
1026 ················await handler.Connection.OpenAsync( cancellationToken ).ConfigureAwait( false );
1027 ················var serverId = ndoConn.Provider.GetConnectionId( handler.Connection );
1028 ················LogIfVerbose( $"Opening connection {serverId} = '{ndoConn.DisplayName}'" );
1029 ············}
1030 ········}
1031
1032 ········/// <summary>
1033 ········/// Event Handler for the ConcurrencyError event of the IPersistenceHandler.
1034 ········/// We try to tell the object which caused the concurrency exception, that a collicion occured.
1035 ········/// This is possible if there is a listener for the CollisionEvent.
1036 ········/// Else we throw an exception.
1037 ········/// </summary>
1038 ········/// <param name="ex">Concurrency Exception which was catched during update.</param>
1039 ········private void OnConcurrencyError(System.Data.DBConcurrencyException ex)
1040 ········{
1041 ············DataRow row = ex.Row;
1042 ············if (row == null || CollisionEvent == null || CollisionEvent.GetInvocationList().Length == 0)
1043 ················throw(ex);
1044 ············if (row.RowState == DataRowState.Detached)
1045 ················return;
1046 ············foreach (Cache.Entry e in cache.LockedObjects)
1047 ············{
1048 ················if (e.row == row)
1049 ················{
1050 ····················CollisionEvent(e.pc);
1051 ····················return;
1052 ················}
1053 ············}
1054 ············throw ex;
1055 ········}
1056
1057
1058 ········private void ReadObject(IPersistenceCapable pc, DataRow row, string[] fieldNames, int startIndex)
1059 ········{
1060 ············Class cl = GetClass(pc);
1061 ············string[] etypes = cl.EmbeddedTypes.ToArray();
1062 ············Dictionary<string,MemberInfo> persistentFields = null;
1063 ············if (etypes.Length > 0)
1064 ············{
1065 ················FieldMap fm = new FieldMap(cl);
1066 ················persistentFields = fm.PersistentFields;
1067 ············}
1068 ············foreach(string s in etypes)
1069 ············{
1070 ················try
1071 ················{
1072 ····················NDO.Mapping.Field f = cl.FindField(s);
1073 ····················if (f == null)
1074 ························continue;
1075 ····················object o = row[f.Column.Name];
1076 ····················string[] arr = s.Split('.');
1077 ····················// Suche Embedded Type-Feld mit Namen arr[0]
1078 ····················BaseClassReflector bcr = new BaseClassReflector(pc.GetType());
1079 ····················FieldInfo parentFi = bcr.GetField(arr[0], BindingFlags.NonPublic | BindingFlags.Instance);
1080 ····················// Hole das Embedded Object
1081 ····················object parentOb = parentFi.GetValue(pc);
1082
1083 ····················if (parentOb == null)
1084 ························throw new Exception(String.Format("Can't read subfield {0} of type {1}, because the field {2} is null. Initialize the field {2} in your default constructor.", s, pc.GetType().FullName, arr[0]));
1085
1086 ····················// Suche darin das Feld mit Namen Arr[1]
1087
1088 ····················FieldInfo childFi = parentFi.FieldType.GetField(arr[1], BindingFlags.NonPublic | BindingFlags.Instance);
1089 ····················Type childType = childFi.FieldType;
1090
1091 ····················// Don't initialize value types, if DBNull is stored in the field.
1092 ····················// Exception: DateTime and Guid.
1093 ····················if (o == DBNull.Value && childType.IsValueType
1094 ························&& childType != typeof(Guid)
1095 ························&& childType != typeof(DateTime))
1096 ························continue;
1097
1098 ····················if (childType == typeof(DateTime))
1099 ····················{
1100 ························if (o == DBNull.Value)
1101 ····························o = DateTime.MinValue;
1102 ····················}
1103 ····················if (childType.IsClass)
1104 ····················{
1105 ························if (o == DBNull.Value)
1106 ····························o = null;
1107 ····················}
1108
1109 ····················if (childType == typeof (Guid))
1110 ····················{
1111 ························if (o == DBNull.Value)
1112 ····························o = Guid.Empty;
1113 ························if (o is string)
1114 ························{
1115 ····························childFi.SetValue(parentOb, new Guid((string)o));
1116 ························}
1117 ························else if (o is Guid)
1118 ························{
1119 ····························childFi.SetValue(parentOb, o);
1120 ························}
1121 ························else if (o is byte[])
1122 ························{
1123 ····························childFi.SetValue(parentOb, new Guid((byte[])o));
1124 ························}
1125 ························else
1126 ····························throw new Exception(string.Format("Can't convert Guid field to column type {0}.", o.GetType().FullName));
1127 ····················}
1128 ····················else if (childType.IsSubclassOf(typeof(System.Enum)))
1129 ····················{
1130 ························object childOb = childFi.GetValue(parentOb);
1131 ························FieldInfo valueFi = childType.GetField("value__");
1132 ························valueFi.SetValue(childOb, o);
1133 ························childFi.SetValue(parentOb, childOb);
1134 ····················}
1135 ····················else
1136 ····················{
1137 ························childFi.SetValue(parentOb, o);
1138 ····················}
1139 ················}
1140 ················catch (Exception ex)
1141 ················{
1142 ····················string msg = "Error while writing the embedded object {0} of an object of type {1}. Check your mapping file.\n{2}";
1143
1144 ····················throw new NDOException(68, string.Format(msg, s, pc.GetType().FullName, ex.Message));
1145 ················}
1146
1147 ············}
1148 ············
1149 ············try
1150 ············{
1151 ················if (cl.HasEncryptedFields)
1152 ················{
1153 ····················foreach (var field in cl.Fields.Where( f => f.Encrypted ))
1154 ····················{
1155 ························string name = field.Column.Name;
1156 ························string s = (string) row[name];
1157 ························string es = AesHelper.Decrypt( s, EncryptionKey );
1158 ························row[name] = es;
1159 ····················}
1160 ················}
1161 ················pc.NDORead(row, fieldNames, startIndex);
1162 ············}
1163 ············catch (Exception ex)
1164 ············{
1165 ················throw new NDOException(69, "Error while writing to a field of an object of type " + pc.GetType().FullName + ". Check your mapping file.\n"
1166 ····················+ ex.Message);
1167 ············}
1168 ········}
1169
1170 ········/// <summary>
1171 ········/// Executes a sql script to generate the database tables.
1172 ········/// The function will execute any sql statements in the script
1173 ········/// which are valid according to the
1174 ········/// rules of the underlying database. Result sets are ignored.
1175 ········/// </summary>
1176 ········/// <param name="scriptFile">The script file to execute.</param>
1177 ········/// <param name="conn">A connection object, containing the connection
1178 ········/// string to the database, which should be altered.</param>
1179 ········/// <returns>A string array with error messages or the string "OK" for each of the statements in the file.</returns>
1180 ········/// <remarks>
1181 ········/// If the Connection object is invalid or null, a NDOException with ErrorNumber 44 will be thrown.
1182 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1183 ········/// Their message property will appear in the result array.
1184 ········/// If the script doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1185 ········/// </remarks>
1186 ········public string[] BuildDatabase( string scriptFile, Connection conn )
1187 ········{
1188 ············return BuildDatabase( scriptFile, conn, Encoding.UTF8 );
1189 ········}
1190
1191 ········/// <summary>
1192 ········/// Executes a sql script to generate the database tables.
1193 ········/// The function will execute any sql statements in the script
1194 ········/// which are valid according to the
1195 ········/// rules of the underlying database. Result sets are ignored.
1196 ········/// </summary>
1197 ········/// <param name="scriptFile">The script file to execute.</param>
1198 ········/// <param name="conn">A connection object, containing the connection
1199 ········/// string to the database, which should be altered.</param>
1200 ········/// <param name="encoding">The encoding of the script file. Default is UTF8.</param>
1201 ········/// <returns>A string array with error messages or the string "OK" for each of the statements in the file.</returns>
1202 ········/// <remarks>
1203 ········/// If the Connection object is invalid or null, a NDOException with ErrorNumber 44 will be thrown.
1204 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1205 ········/// Their message property will appear in the result array.
1206 ········/// If the script doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1207 ········/// </remarks>
1208 ········public string[] BuildDatabase(string scriptFile, Connection conn, Encoding encoding)
1209 ········{
1210 ············StreamReader sr = new StreamReader(scriptFile, encoding);
1211 ············string s = sr.ReadToEnd();
1212 ············sr.Close();
1213 ············string[] arr = s.Split(';');
1214 ············string last = arr[arr.Length - 1];
1215 ············bool lastInvalid = (last == null || last.Trim() == string.Empty);
1216 ············string[] result = new string[arr.Length - (lastInvalid ? 1 : 0)];
1217 ············using (var handler = GetSqlPassThroughHandler())
1218 ············{
1219 ················int i = 0;
1220 ················string ok = "OK";
1221 ················foreach (string statement in arr)
1222 ················{
1223 ····················if (statement != null && statement.Trim() != string.Empty)
1224 ····················{
1225 ························try
1226 ························{
1227 ····························handler.Execute(statement);
1228 ····························result[i] = ok;
1229 ························}
1230 ························catch (Exception ex)
1231 ························{
1232 ····························result[i] = ex.Message;
1233 ························}
1234 ····················}
1235 ····················i++;
1236 ················}
1237 ················CheckEndTransaction(true);
1238 ············}
1239 ············return result;
1240 ········}
1241
1242 ········/// <summary>
1243 ········/// Executes a sql script to generate the database tables.
1244 ········/// The function will execute any sql statements in the script
1245 ········/// which are valid according to the
1246 ········/// rules of the underlying database. Result sets are ignored.
1247 ········/// </summary>
1248 ········/// <param name="scriptFile">The script file to execute.</param>
1249 ········/// <returns></returns>
1250 ········/// <remarks>
1251 ········/// This function takes the first Connection object in the Connections list
1252 ········/// of the Mapping file und executes the script using that connection.
1253 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1254 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1255 ········/// Their message property will appear in the result array.
1256 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1257 ········/// </remarks>
1258 ········public string[] BuildDatabase(string scriptFile)
1259 ········{
1260 ············if (!File.Exists(scriptFile))
1261 ················throw new NDOException(48, "Script file " + scriptFile + " doesn't exist.");
1262 ············if (!this.mappings.Connections.Any())
1263 ················throw new NDOException(48, "Mapping file doesn't define a connection.");
1264 ············Connection conn = new Connection( this.mappings );
1265 ············Connection originalConnection = (Connection)this.mappings.Connections.First();
1266 ············conn.Name = OnNewConnection( originalConnection );
1267 ············conn.Type = originalConnection.Type;
1268 ············//Connection conn = (Connection) this.mappings.Connections[0];
1269 ············return BuildDatabase(scriptFile, conn);
1270 ········}
1271
1272 ········/// <summary>
1273 ········/// Executes a sql script to generate the database tables.
1274 ········/// The function will execute any sql statements in the script
1275 ········/// which are valid according to the
1276 ········/// rules of the underlying database. Result sets are ignored.
1277 ········/// </summary>
1278 ········/// <returns>
1279 ········/// A string array, containing the error messages produced by the statements
1280 ········/// contained in the script.
1281 ········/// </returns>
1282 ········/// <remarks>
1283 ········/// The sql script is assumed to be the executable name of the entry assembly with the
1284 ········/// extension .ndo.sql. Use BuildDatabase(string) to provide a path to a script.
1285 ········/// If the executable name can't be determined a NDOException with ErrorNumber 49 will be thrown.
1286 ········/// This function takes the first Connection object in the Connections list
1287 ········/// of the Mapping file und executes the script using that connection.
1288 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1289 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1290 ········/// Their message property will appear in the result array.
1291 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1292 ········/// </remarks>
1293 ········public string[] BuildDatabase()
1294 ········{
1295 ············Assembly ass = Assembly.GetEntryAssembly();
1296 ············if (ass == null)
1297 ················throw new NDOException(49, "Can't determine the path of the entry assembly - please pass a sql script path as argument to BuildDatabase.");
1298 ············string file = Path.ChangeExtension(ass.Location, ".ndo.sql");
1299 ············return BuildDatabase(file);
1300 ········}
1301
1302 ········/// <summary>
1303 ········/// Gets a SqlPassThroughHandler object which can be used to execute raw Sql statements.
1304 ········/// </summary>
1305 ········/// <param name="conn">Optional: The NDO-Connection to the database to be used.</param>
1306 ········/// <returns>An ISqlPassThroughHandler implementation</returns>
1307 ········public ISqlPassThroughHandler GetSqlPassThroughHandler( Connection conn = null )
1308 ········{
1309 ············if (!this.mappings.Connections.Any())
1310 ················throw new NDOException( 48, "Mapping file doesn't define a connection." );
1311 ············if (conn == null)
1312 ············{
1313 ················conn = new Connection( this.mappings );
1314 ················Connection originalConnection = (Connection) this.mappings.Connections.First();
1315 ················conn.Name = OnNewConnection( originalConnection );
1316 ················conn.Type = originalConnection.Type;
1317 ············}
1318
1319 ············return new SqlPassThroughHandler( this, conn );
1320 ········}
1321
1322 ········/// <summary>
1323 ········/// Gets a SqlPassThroughHandler object which can be used to execute raw Sql statements.
1324 ········/// </summary>
1325 ········/// <param name="predicate">A predicate defining which connection has to be used.</param>
1326 ········/// <returns>An ISqlPassThroughHandler implementation</returns>
1327 ········public ISqlPassThroughHandler GetSqlPassThroughHandler( Func<Connection, bool> predicate )
1328 ········{
1329 ············if (!this.mappings.Connections.Any())
1330 ················throw new NDOException( 48, "The Mapping file doesn't define a connection." );
1331 ············Connection conn = this.mappings.Connections.FirstOrDefault( predicate );
1332 ············if (conn == null)
1333 ················throw new NDOException( 48, "The Mapping file doesn't define a connection with this predicate." );
1334 ············return GetSqlPassThroughHandler( conn );
1335 ········}
1336
1337 ········/// <summary>
1338 ········/// Executes a xml script to generate the database tables.
1339 ········/// The function will generate and execute sql statements to perform
1340 ········/// the changes described by the xml.
1341 ········/// </summary>
1342 ········/// <returns></returns>
1343 ········/// <remarks>
1344 ········/// The script file is the first file found with the search string [AssemblyNameWithoutExtension].ndodiff.[SchemaVersion].xml.
1345 ········/// If several files match the search string biggest file name in the default sort order will be executed.
1346 ········/// This function takes the first Connection object in the Connections list
1347 ········/// of the Mapping file und executes the script using that connection.
1348 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1349 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1350 ········/// Their message property will appear in the result string array.
1351 ········/// If no script file exists, a NDOException with ErrorNumber 48 will be thrown.
1352 ········/// Note that an additional command is executed, which will update the NDOSchemaVersion entry.
1353 ········/// </remarks>
1354 ········public string[] PerformSchemaTransitions()
1355 ········{
1356 ············Assembly ass = Assembly.GetEntryAssembly();
1357 ············if (ass == null)
1358 ················throw new NDOException(49, "Can't determine the path of the entry assembly - please pass a sql script path as argument to PerformSchemaTransitions.");
1359 ············string mask = Path.GetFileNameWithoutExtension( ass.Location ) + ".ndodiff.*.xml";
1360 ············List<string> fileNames = Directory.GetFiles( Path.GetDirectoryName( ass.Location ), mask ).ToList();
1361 ············if (fileNames.Count == 0)
1362 ················return new String[] { String.Format( "No xml script file with a name like {0} found.", mask ) };
1363 ············if (fileNames.Count > 1)
1364 ················fileNames.Sort( ( fn1, fn2 ) => CompareFileName( fn1, fn2 ) );
1365 ············return PerformSchemaTransitions( fileNames[0] );
1366 ········}
1367
1368
1369 ········/// <summary>
1370 ········/// Executes a xml script to generate the database tables.
1371 ········/// The function will generate and execute sql statements to perform
1372 ········/// the changes described by the xml.
1373 ········/// </summary>
1374 ········/// <param name="scriptFile">The script file to execute.</param>
1375 ········/// <returns></returns>
1376 ········/// <remarks>
1377 ········/// This function takes the first Connection object in the Connections list
1378 ········/// of the Mapping file und executes the script using that connection.
1379 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1380 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1381 ········/// Their message property will appear in the result string array.
1382 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1383 ········/// Note that an additional command is executed, which will update the NDOSchemaVersion entry.
1384 ········/// </remarks>
1385 ········public string[] PerformSchemaTransitions(string scriptFile)
1386 ········{
1387 ············if (!File.Exists(scriptFile))
1388 ················throw new NDOException(48, "Script file " + scriptFile + " doesn't exist.");
1389
1390 ············if (!this.mappings.Connections.Any())
1391 ················throw new NDOException(48, "Mapping file doesn't define any connection.");
1392 ············Connection conn = new Connection( mappings );
1393 ············Connection originalConnection = mappings.Connections.First();
1394 ············conn.Name = OnNewConnection( originalConnection );
1395 ············conn.Type = originalConnection.Type;
1396 ············return PerformSchemaTransitions(scriptFile, conn);
1397 ········}
1398
1399
1400 ········int CompareFileName( string fn1, string fn2)
1401 ········{
1402 ············Regex regex = new Regex( @"ndodiff\.(.+)\.xml" );
1403 ············Match match = regex.Match( fn1 );
1404 ············string v1 = match.Groups[1].Value;
1405 ············match = regex.Match( fn2 );
1406 ············string v2 = match.Groups[1].Value;
1407 ············return new Version( v2 ).CompareTo( new Version( v1 ) );
1408 ········}
1409
1410 ········Guid[] GetSchemaIds(Connection ndoConn, string schemaName, IProvider provider)
1411 ········{
1412 ············var connection = provider.NewConnection( ndoConn.Name );
1413 ············var resultList = new List<Guid>();
1414
1415 ············using (var handler = GetSqlPassThroughHandler())
1416 ············{
1417 ················string[] TableNames = provider.GetTableNames( connection );
1418 ················if (TableNames.Any( t => String.Compare( t, "NDOSchemaIds", true ) == 0 ))
1419 ················{
1420 ····················var schemaIds = provider.GetQualifiedTableName("NDOSchemaIds");
1421 ····················var sn = provider.GetQuotedName("SchemaName");
1422 ····················var id = provider.GetQuotedName("Id");
1423 ····················string sql = $"SELECT {id} from {schemaIds} WHERE {sn} ";
1424 ····················if (String.IsNullOrEmpty(schemaName))
1425 ························sql += "IS NULL;";
1426 ····················else
1427 ························sql += $"LIKE '{schemaName}'";
1428
1429 ····················using(IDataReader dr = handler.Execute(sql, true))
1430 ····················{
1431 ························while (dr.Read())
1432 ····························resultList.Add( dr.GetGuid( 0 ) );
1433 ····················}
1434 ················}
1435 ················else
1436 ················{
1437 ····················SchemaTransitionGenerator schemaTransitionGenerator = new SchemaTransitionGenerator( ProviderFactory, ndoConn.Type, this.mappings );
1438 ····················var gt = typeof(Guid);
1439 ····················var gtype = $"{gt.FullName},{ new AssemblyName( gt.Assembly.FullName ).Name }";
1440 ····················var st = typeof(String);
1441 ····················var stype = $"{st.FullName},{ new AssemblyName( st.Assembly.FullName ).Name }";
1442 ····················var dt = typeof(DateTime);
1443 ····················var dtype = $"{st.FullName},{ new AssemblyName( st.Assembly.FullName ).Name }";
1444 ····················string transition = $@"<NdoSchemaTransition>
1445 ····<CreateTable name=""NDOSchemaIds"">
1446 ······<CreateColumn name=""SchemaName"" type=""{stype}"" allowNull=""True"" />
1447 ······<CreateColumn name=""Id"" type=""{gtype}"" size=""36"" isPrimary=""True"" />
1448 ······<CreateColumn name=""InsertTime"" type=""{dtype}"" size=""36"" />
1449 ····</CreateTable>
1450 </NdoSchemaTransition>";
1451 ····················XElement transitionElement = XElement.Parse(transition);
1452
1453 ····················string sql = schemaTransitionGenerator.Generate( transitionElement );
1454 ····················handler.Execute(sql);
1455 ················}
1456 ················handler.CommitTransaction();
1457 ············}
1458
1459 ············return resultList.ToArray();
1460 ········}
1461
1462 ········/// <summary>
1463 ········/// Executes a xml script to generate the database tables.
1464 ········/// The function will generate and execute sql statements to perform
1465 ········/// the changes described by the xml.
1466 ········/// </summary>
1467 ········/// <param name="scriptFile">The xml script file.</param>
1468 ········/// <param name="ndoConn">The connection to be used to perform the schema changes.</param>
1469 ········/// <returns>A list of strings about the states of the different schema change commands.</returns>
1470 ········/// <remarks>Note that an additional command is executed, which will update the NDOSchemaVersion entry.</remarks>
1471 ········public string[] PerformSchemaTransitions(string scriptFile, Connection ndoConn)
1472 ········{
1473 ············string schemaName = null;
1474 ············// Gespeicherte Version ermitteln.
1475 ············XElement transitionElements = XElement.Load( scriptFile );
1476 ············if (transitionElements.Attribute( "schemaName" ) != null)
1477 ················schemaName = transitionElements.Attribute( "schemaName" ).Value;
1478
1479 ············IProvider provider = this.mappings.GetProvider( ndoConn );
1480 ············var installedIds = GetSchemaIds( ndoConn, schemaName, provider );
1481 ············var newIds = new List<Guid>();
1482 ············SchemaTransitionGenerator schemaTransitionGenerator = new SchemaTransitionGenerator( ProviderFactory, ndoConn.Type, this.mappings );
1483
1484 ············// dtLiteral contains the leading and trailing quotes
1485 ············var dtLiteral = provider.GetSqlLiteral( DateTime.Now );
1486 ············var ndoSchemaIds = provider.GetQualifiedTableName("NDOSchemaIds");
1487 ············var schName = provider.GetQuotedName("SchemaName");
1488 ············var idCol = provider.GetQuotedName("Id");
1489 ············var insertTime = provider.GetQuotedName("InsertTime");
1490 ············var results = new List<string>();
1491
1492 ············// Each transitionElement gets it's own transaction.
1493 ············// The insert into NDOSchemaIds is part of the transaction.
1494 ············// If an error occurs, InternalPerformSchemaTransitions aborts the transaction.
1495 ············foreach (XElement transitionElement in transitionElements.Elements( "NdoSchemaTransition" ))
1496 ············{
1497 ················var id = transitionElement.Attribute("id")?.Value;
1498 ················if (id == null)
1499 ····················continue;
1500 ················var gid = new Guid(id);
1501 ················if (installedIds.Contains( gid ))
1502 ····················continue;
1503
1504 ················var sb = new StringBuilder();
1505 ················sb.Append( schemaTransitionGenerator.Generate( transitionElement ) );
1506 ················newIds.Add( gid );
1507
1508 ················if (schemaName != null)
1509 ····················sb.Append( $"INSERT INTO {ndoSchemaIds} ({schName},{idCol},{insertTime}) VALUES ('{schemaName}','{gid}',{dtLiteral});" );
1510 ················else
1511 ····················sb.Append( $"INSERT INTO {ndoSchemaIds} ({schName},{idCol},{insertTime}) VALUES (NULL,'{gid}',{dtLiteral});" );
1512
1513 ················results.AddRange( InternalPerformSchemaTransitions( ndoConn, sb.ToString() ) );
1514 ············}
1515
1516 ············return results.ToArray();
1517 ········}
1518
1519 ········private string[] InternalPerformSchemaTransitions( Connection ndoConn, string sql )
1520 ········{
1521 ············string[] arr = sql.Split( ';' );
1522
1523 ············string last = arr[arr.Length - 1];
1524 ············bool lastInvalid = (last == null || last.Trim() == string.Empty);
1525 ············string[] result = new string[arr.Length - (lastInvalid ? 1 : 0)];
1526 ············int i = 0;
1527 ············string ok = "OK";
1528 ············using (var handler = GetSqlPassThroughHandler())
1529 ············{
1530 ················handler.BeginTransaction();
1531 ················var doCommit = true;
1532 ················foreach (string statement in arr)
1533 ················{
1534 ····················if (!String.IsNullOrWhiteSpace(statement))
1535 ····················{
1536 ························try
1537 ························{
1538 ····························handler.Execute( statement.Trim() );
1539 ····························result[i] = ok;
1540 ························}
1541 ························catch (Exception ex)
1542 ························{
1543 ····························result[i] = ex.Message;
1544 ····························doCommit = false;
1545 ························}
1546 ····················}
1547 ····················i++;
1548 ················}
1549 ················if (doCommit)
1550 ····················handler.CommitTransaction();
1551 ················else
1552 ····················AbortTransaction();
1553 ············}
1554
1555 ············return result;
1556 ········}
1557 ········
1558 ········/// <summary>
1559 ········/// Transfers Data from the object to the DataRow
1560 ········/// </summary>
1561 ········/// <param name="pc"></param>
1562 ········/// <param name="row"></param>
1563 ········/// <param name="fieldNames"></param>
1564 ········/// <param name="startIndex"></param>
1565 ········protected virtual void WriteObject(IPersistenceCapable pc, DataRow row, string[] fieldNames, int startIndex)
1566 ········{
1567 ············Class cl = GetClass( pc );
1568 ············try
1569 ············{
1570 ················pc.NDOWrite(row, fieldNames, startIndex);
1571 ················if (cl.HasEncryptedFields)
1572 ················{
1573 ····················foreach (var field in cl.Fields.Where( f => f.Encrypted ))
1574 ····················{
1575 ························string name = field.Column.Name;
1576 ························string s = (string) row[name];
1577 ························string es = AesHelper.Encrypt( s, EncryptionKey );
1578 ························row[name] = es;
1579 ····················}
1580 ················}
1581 ············}
1582 ············catch (Exception ex)
1583 ············{
1584 ················throw new NDOException(70, "Error while reading a field of an object of type " + pc.GetType().FullName + ". Check your mapping file.\n"
1585 ····················+ ex.Message);
1586 ············}
1587
1588 ············if (cl.TypeNameColumn != null)
1589 ············{
1590 ················Type t = pc.GetType();
1591 ················row[cl.TypeNameColumn.Name] = t.FullName + "," + t.Assembly.GetName().Name;
1592 ············}
1593
1594 ············var etypes = cl.EmbeddedTypes;
1595 ············foreach(string s in etypes)
1596 ············{
1597 ················try
1598 ················{
1599 ····················NDO.Mapping.Field f = cl.FindField(s);
1600 ····················if (f == null)
1601 ························continue;
1602 ····················string[] arr = s.Split('.');
1603 ····················// Suche Feld mit Namen arr[0] als object
1604 ····················BaseClassReflector bcr = new BaseClassReflector(pc.GetType());
1605 ····················FieldInfo parentFi = bcr.GetField(arr[0], BindingFlags.NonPublic | BindingFlags.Instance);
1606 ····················Object parentOb = parentFi.GetValue(pc);
1607 ····················if (parentOb == null)
1608 ························throw new Exception(String.Format("The field {0} is null. Initialize the field in your default constructor.", arr[0]));
1609 ····················// Suche darin das Feld mit Namen Arr[1]
1610 ····················FieldInfo childFi = parentFi.FieldType.GetField(arr[1], BindingFlags.NonPublic | BindingFlags.Instance);
1611 ····················object o = childFi.GetValue(parentOb);
1612 ····················if (o == null
1613 ························|| o is DateTime && (DateTime) o == DateTime.MinValue
1614 ························|| o is Guid && (Guid) o == Guid.Empty)
1615 ························o = DBNull.Value;
1616 ····················row[f.Column.Name] = o;
1617 ················}
1618 ················catch (Exception ex)
1619 ················{
1620 ····················string msg = "Error while reading the embedded object {0} of an object of type {1}. Check your mapping file.\n{2}";
1621
1622 ····················throw new NDOException(71, string.Format(msg, s, pc.GetType().FullName, ex.Message));
1623 ················}
1624 ············}
1625 ········}
1626
1627 ········/// <summary>
1628 ········/// Check, if the specific field is loaded. If not, LoadData will be called.
1629 ········/// </summary>
1630 ········/// <param name="o">The parent object.</param>
1631 ········/// <param name="fieldOrdinal">A number to identify the field.</param>
1632 ········public virtual void LoadField(object o, int fieldOrdinal)
1633 ········{
1634 ············IPersistenceCapable pc = CheckPc(o);
1635 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
1636 ············{
1637 ················LoadState ls = pc.NDOLoadState;
1638 ················if (ls.FieldLoadState != null)
1639 ················{
1640 ····················if (ls.FieldLoadState[fieldOrdinal])
1641 ························return;
1642 ················}
1643 ················else
1644 ················{
1645 ····················ls.FieldLoadState = new BitArray( GetClass( pc ).Fields.Count() );
1646 ················}
1647 ················LoadData(o);
1648 ········}
1649 ········}
1650
1651 #pragma warning disable 419
1652 ········/// <summary>
1653 ········/// Load the data of a persistent object. This forces the transition of the object state from hollow to persistent.
1654 ········/// </summary>
1655 ········/// <param name="o">The hollow object.</param>
1656 ········/// <remarks>Note, that the relations won't be resolved with this function, with one Exception: 1:1 relations without mapping table will be resolved during LoadData. In all other cases, use <see cref="LoadRelation">LoadRelation</see>, to force resolving a relation.<seealso cref="NDOObjectState"/></remarks>
1657 #pragma warning restore 419
1658 ········public void LoadData( object o )
1659 ········{
1660 ············LoadDataAsync( o ).ConfigureAwait( false ).GetAwaiter().GetResult();
1661 ········}
1662
1663 #pragma warning disable 419
1664 ········/// <summary>
1665 ········/// Load the data of a persistent object asynchronously. This forces the transition of the object state from hollow to persistent.
1666 ········/// </summary>
1667 ········/// <param name="o">The hollow object.</param>
1668 ········/// <param name="cancellationToken">A token to cancel the operation</param>
1669 ········/// <remarks>Note, that the relations won't be resolved with this function, with one Exception: 1:1 relations without mapping table will be resolved during LoadData. In all other cases, use <see cref="LoadRelationAsync(object, string, bool, CancellationToken)">LoadRelationAsync</see>, to force resolving a relation.<seealso cref="NDOObjectState"/></remarks>
1670 #pragma warning restore 419
1671 ········public virtual async Task LoadDataAsync( object o, CancellationToken cancellationToken = default )
1672 ········{
1673 ············using (EnterOperation())
1674 ············{
1675 ················await LoadDataInternalAsync( o, cancellationToken ).ConfigureAwait( false );
1676 ············}
1677 ········}
1678
1679 ········async Task LoadDataInternalAsync( object o, CancellationToken cancellationToken )
1680 ········{
1681 ············IPersistenceCapable pc = CheckPc(o);
1682 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Hollow, "Can only load hollow objects");
1683 ············if (pc.NDOObjectState != NDOObjectState.Hollow)
1684 ················return;
1685 ············Class cl = GetClass(pc);
1686 ············IQuery q;
1687 ············q = CreateOidQuery(pc, cl);
1688 ············cache.UpdateCache(pc); // Make sure the object is in the cache
1689
1690 ············var objects = await q.ExecuteAsync( cancellationToken ).ConfigureAwait( false );
1691 ············var count = objects.Count;
1692
1693 ············if (count > 1)
1694 ············{
1695 ················throw new NDOException( 72, "Load Data: " + count + " result objects with the same oid" );
1696 ············}
1697 ············else if (count == 0)
1698 ············{
1699 ················if (ObjectNotPresentEvent == null || !ObjectNotPresentEvent(pc))
1700 ················throw new NDOException( 72, "LoadData: Object " + pc.NDOObjectId.Dump() + " is not present in the database." );
1701 ············}
1702 ········}
1703
1704 ········/// <summary>
1705 ········/// Creates a new IQuery object for the given type
1706 ········/// </summary>
1707 ········/// <param name="t"></param>
1708 ········/// <param name="oql"></param>
1709 ········/// <param name="hollow"></param>
1710 ········/// <param name="queryLanguage"></param>
1711 ········/// <returns></returns>
1712 ········public IQuery NewQuery(Type t, string oql, bool hollow = false, QueryLanguage queryLanguage = QueryLanguage.NDOql)
1713 ········{
1714 ············Type template = typeof( NDOQuery<object> ).GetGenericTypeDefinition();
1715 ············Type qt = template.MakeGenericType( t );
1716 ············return (IQuery)Activator.CreateInstance( qt, this, oql, hollow, queryLanguage );
1717 ········}
1718
1719 ········private IQuery CreateOidQuery(IPersistenceCapable pc, Class cl)
1720 ········{
1721 ············ArrayList parameters = new ArrayList();
1722 ············string oql = "oid = {0}";
1723 ············IQuery q = NewQuery(pc.GetType(), oql, false);
1724 ············q.Parameters.Add( pc.NDOObjectId );
1725 ············q.AllowSubclasses = false;
1726 ············return q;
1727 ········}
1728
1729 ········/// <summary>
1730 ········/// Mark the object dirty. The current state is
1731 ········/// saved in a DataRow, which is stored in the DS. This is done, to allow easy rollback later. Also, the
1732 ········/// object is locked in the cache.
1733 ········/// </summary>
1734 ········/// <param name="pc"></param>
1735 ········internal virtual void MarkDirty(IPersistenceCapable pc)
1736 ········{
1737 ············if (pc.NDOObjectState != NDOObjectState.Persistent)
1738 ················return;
1739 ············SaveObjectState(pc);
1740 ············pc.NDOObjectState = NDOObjectState.PersistentDirty;
1741 ········}
1742
1743 ········/// <summary>
1744 ········/// Mark the object dirty, but make sure first, that the object is loaded.
1745 ········/// The current or loaded state is saved in a DataRow, which is stored in the DS.
1746 ········/// This is done, to allow easy rollback later. Also, the
1747 ········/// object is locked in the cache.
1748 ········/// </summary>
1749 ········/// <param name="pc"></param>
1750 ········internal void LoadAndMarkDirty(IPersistenceCapable pc)
1751 ········{
1752 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient, "Transient objects can't be marked as dirty.");
1753
1754 ············if(pc.NDOObjectState == NDOObjectState.Deleted)
1755 ············{
1756 ················throw new NDOException(73, "LoadAndMarkDirty: Access to deleted objects is not allowed.");
1757 ············}
1758
1759 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
1760 ················LoadData(pc);
1761
1762 ············// state is either (Created), Persistent, PersistentDirty
1763 ············if(pc.NDOObjectState == NDOObjectState.Persistent)
1764 ············{
1765 ················MarkDirty(pc);
1766 ············}
1767 ········}
1768
1769
1770
1771 ········/// <summary>
1772 ········/// Save current object state in DS and lock the object in the cache.
1773 ········/// The saved state can be used later to retrieve the original object value if the
1774 ········/// current transaction is aborted. Also the state of all relations (not related objects) is stored.
1775 ········/// </summary>
1776 ········/// <param name="pc">The object that should be saved</param>
1777 ········/// <param name="isDeleting">Determines, if the object is about being deletet.</param>
1778 ········/// <remarks>
1779 ········/// In a data row there are the following things:
1780 ········/// Item································Responsible for writing
1781 ········/// State (own, inherited, embedded)····WriteObject
1782 ········/// TimeStamp····························NDOPersistenceHandler
1783 ········/// Oid····································WriteId
1784 ········/// Foreign Keys and their Type Codes····WriteForeignKeys
1785 ········/// </remarks>
1786 ········protected virtual void SaveObjectState(IPersistenceCapable pc, bool isDeleting = false)
1787 ········{
1788 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Persistent, "Object must be unmodified and persistent but is " + pc.NDOObjectState);
1789 ············
1790 ············DataTable table = GetTable(pc);
1791 ············DataRow row = table.NewRow();
1792 ············Class cl = GetClass(pc);
1793 ············WriteObject(pc, row, cl.ColumnNames, 0);
1794 ············WriteIdToRow(pc, row);
1795 ············if (!isDeleting)
1796 ················WriteLostForeignKeysToRow(cl, pc, row);
1797 ············table.Rows.Add(row);
1798 ············row.AcceptChanges();
1799 ············
1800 ············var relations = CollectRelationStates(pc);
1801 ············cache.Lock(pc, row, relations);
1802 ········}
1803
1804 ········private void SaveFakeRow(IPersistenceCapable pc)
1805 ········{
1806 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Hollow, "Object must be hollow but is " + pc.NDOObjectState);
1807 ············
1808 ············DataTable table = GetTable(pc);
1809 ············DataRow row = table.NewRow();
1810 ············Class pcClass = GetClass(pc);
1811 ············row.SetColumnError(GetFakeRowOidColumnName(pcClass), hollowMarker);
1812 ············Class cl = GetClass(pc);
1813 ············//WriteObject(pc, row, cl.FieldNames, 0);
1814 ············WriteIdToRow(pc, row);
1815 ············table.Rows.Add(row);
1816 ············row.AcceptChanges();
1817 ············
1818 ············cache.Lock(pc, row, null);
1819 ········}
1820
1821 ········/// <summary>
1822 ········/// This defines one column of the row, in which we use the
1823 ········/// ColumnError property to determine, if the row is a fake row.
1824 ········/// </summary>
1825 ········/// <param name="pcClass"></param>
1826 ········/// <returns></returns>
1827 ········private string GetFakeRowOidColumnName(Class pcClass)
1828 ········{
1829 ············// In case of several OidColumns the first column defined in the mapping
1830 ············// will be the one, holding the fake row info.
1831 ············return ((OidColumn)pcClass.Oid.OidColumns[0]).Name;
1832 ········}
1833
1834 ········private bool IsFakeRow(Class cl, DataRow row)
1835 ········{
1836 ············return (row.GetColumnError(GetFakeRowOidColumnName(cl)) == hollowMarker);
1837 ········}
1838
1839 ········/// <summary>
1840 ········/// Make a list of objects persistent.
1841 ········/// </summary>
1842 ········/// <param name="list">the list of IPersistenceCapable objects</param>
1843 ········public void MakePersistent(System.Collections.IList list)
1844 ········{
1845 ············foreach (IPersistenceCapable pc in list)
1846 ············{
1847 ················MakePersistent(pc);
1848 ············}
1849 ········}
1850
1851 ········/// <summary>
1852 ········/// Save state of related objects in the cache. Only the list itself is duplicated and stored. The related objects are
1853 ········/// not duplicated.
1854 ········/// </summary>
1855 ········/// <param name="pc">the parent object of all relations</param>
1856 ········/// <returns></returns>
1857 ········protected internal virtual List<KeyValuePair<Relation,object>> CollectRelationStates(IPersistenceCapable pc)
1858 ········{
1859 ············// Save state of relations
1860 ············Class c = GetClass(pc);
1861 ············List<KeyValuePair<Relation, object>> relations = new List<KeyValuePair<Relation, object>>( c.Relations.Count());
1862 ············foreach(Relation r in c.Relations)
1863 ············{
1864 ················if (r.Multiplicity == RelationMultiplicity.Element)
1865 ················{
1866 ····················relations.Add( new KeyValuePair<Relation, object>( r, mappings.GetRelationField( pc, r.FieldName ) ) );
1867 ················}
1868 ················else
1869 ················{
1870 ····················IList l = mappings.GetRelationContainer(pc, r);
1871 ····················if(l != null)
1872 ····················{
1873 ························l = (IList) ListCloner.CloneList(l);
1874 ····················}
1875 ····················relations.Add( new KeyValuePair<Relation, object>( r, l ) );
1876 ················}
1877 ············}
1878
1879 ············return relations;
1880 ········}
1881
1882
1883 ········/// <summary>
1884 ········/// Restore the saved relations.··Note that the objects are not restored as this is handled transparently
1885 ········/// by the normal persistence mechanism. Only the number and order of objects are restored, e.g. the state,
1886 ········/// the list had at the beginning of the transaction.
1887 ········/// </summary>
1888 ········/// <param name="pc"></param>
1889 ········/// <param name="relations"></param>
1890 ········private void RestoreRelatedObjects(IPersistenceCapable pc, List<KeyValuePair<Relation, object>> relations )
1891 ········{
1892 ············Class c = GetClass(pc);
1893
1894 ············foreach(var entry in relations)
1895 ············{
1896 ················var r = entry.Key;
1897 ················if (r.Multiplicity == RelationMultiplicity.Element)
1898 ················{
1899 ····················mappings.SetRelationField(pc, r.FieldName, entry.Value);
1900 ················}
1901 ················else
1902 ················{
1903 ····················if (pc.NDOGetLoadState(r.Ordinal))
1904 ····················{
1905 ························// Help GC by clearing lists
1906 ························IList l = mappings.GetRelationContainer(pc, r);
1907 ························if(l != null)
1908 ························{
1909 ····························l.Clear();
1910 ························}
1911 ························// Restore relation
1912 ························mappings.SetRelationContainer(pc, r, (IList)entry.Value);
1913 ····················}
1914 ················}
1915 ············}
1916 ········}
1917
1918
1919 ········/// <summary>
1920 ········/// Generates a query for related objects without mapping table.
1921 ········/// Note: this function can't be called in polymorphic scenarios,
1922 ········/// since they need a mapping table.
1923 ········/// </summary>
1924 ········/// <returns></returns>
1925 ········async Task<IList> QueryRelatedObjectsAsync( IPersistenceCapable pc, Relation r, IList l, bool hollow, CancellationToken cancellationToken )
1926 ········{
1927 ············// At this point of execution we know,
1928 ············// that the target type is not polymorphic and is not 1:1.
1929
1930 ············// We can't fetch these objects with an NDOql query
1931 ············// since this would require a relation in the opposite direction
1932
1933 ············IList relatedObjects;
1934 ············if (l != null)
1935 ················relatedObjects = l;
1936 ············else
1937 ················relatedObjects = mappings.CreateRelationContainer( pc, r );
1938
1939 ············Type t = r.ReferencedType;
1940 ············Class cl = GetClass( t );
1941 ············var provider = cl.Provider;
1942
1943 ············StringBuilder sb = new StringBuilder("SELECT * FROM ");
1944 ············var relClass = GetClass( r.ReferencedType );
1945 ············sb.Append( GetClass( r.ReferencedType ).GetQualifiedTableName() );
1946 ············sb.Append( " WHERE " );
1947 ············int i = 0;
1948 ············List<object> parameters = new List<object>();
1949 ············new ForeignKeyIterator( r ).Iterate( delegate ( ForeignKeyColumn fkColumn, bool isLastElement )
1950 ·············· {
1951 ·················· sb.Append( fkColumn.GetQualifiedName(relClass) );
1952 ·················· sb.Append( " = {" );
1953 ·················· sb.Append(i);
1954 ·················· sb.Append( '}' );
1955 ·················· parameters.Add( pc.NDOObjectId.Id[i] );
1956 ·················· if (!isLastElement)
1957 ······················ sb.Append( " AND " );
1958 ·················· i++;
1959 ·············· } );
1960
1961 ············if (!(String.IsNullOrEmpty( r.ForeignKeyTypeColumnName )))
1962 ············{
1963 ················sb.Append( " AND " );
1964 ················sb.Append( provider.GetQualifiedTableName( relClass.TableName + "." + r.ForeignKeyTypeColumnName ) );
1965 ················sb.Append( " = " );
1966 ················sb.Append( pc.NDOObjectId.Id.TypeId );
1967 ············}
1968
1969 ············IQuery q = NewQuery( t, sb.ToString(), hollow, Query.QueryLanguage.Sql );
1970
1971 ············foreach (var p in parameters)
1972 ············{
1973 ················q.Parameters.Add( p );
1974 ············}
1975
1976 ············q.AllowSubclasses = false;··// Remember: polymorphic relations always have a mapping table
1977
1978 ············IList l2 = await q.ExecuteAsync( cancellationToken ).ConfigureAwait( false );
1979
1980 ············foreach (object o in l2)
1981 ················relatedObjects.Add( o );
1982
1983 ············return relatedObjects;
1984 ········}
1985
1986
1987 ········/// <summary>
1988 ········/// Resolves an relation. The loaded objects will be hollow.
1989 ········/// </summary>
1990 ········/// <param name="o">The parent object.</param>
1991 ········/// <param name="fieldName">The field name of the container or variable, which represents the relation.</param>
1992 ········/// <param name="hollow">True, if the fetched objects should be hollow.</param>
1993 ········/// <remarks>Note: 1:1 relations without mapping table will be resolved during the transition from the hollow to the persistent state. To force this transition, use the <see cref="LoadData">LoadData</see> function.<seealso cref="LoadData"/></remarks>
1994 ········public void LoadRelation(object o, string fieldName, bool hollow)
1995 ········{
1996 ············LoadRelationAsync( o, fieldName, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
1997 ········}
1998
1999 ········/// <summary>
2000 ········/// Resolves an relation asynchronously.
2001 ········/// </summary>
2002 ········/// <param name="o">The parent object.</param>
2003 ········/// <param name="fieldName">The field name of the container or variable, which represents the relation.</param>
2004 ········/// <param name="hollow">True, if the fetched objects should be hollow.</param>
2005 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2006 ········/// <remarks>Note: 1:1 relations without mapping table will be resolved during the transition from the hollow to the persistent state. To force this transition, use the <see cref="LoadDataAsync">LoadDataAsync</see> function.<seealso cref="LoadDataAsync"/></remarks>
2007 ········public virtual async Task LoadRelationAsync( object o, string fieldName, bool hollow, CancellationToken cancellationToken = default )
2008 ········{
2009 ············using (EnterOperation())
2010 ············{
2011 ················IPersistenceCapable pc = CheckPc(o);
2012 ················await LoadRelationInternalAsync( pc, fieldName, hollow, cancellationToken ).ConfigureAwait( false );
2013 ············}
2014 ········}
2015
2016 ········
2017
2018 ········internal IList LoadRelation(IPersistenceCapable pc, Relation r, bool hollow)
2019 ········{
2020 ············return LoadRelationAsync( pc, r, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
2021 ········}
2022
2023 ········internal async Task<IList> LoadRelationAsync( IPersistenceCapable pc, Relation r, bool hollow, CancellationToken cancellationToken = default )
2024 ········{
2025 ············using (EnterOperation())
2026 ············{
2027 ················return await LoadRelationCoreAsync( pc, r, hollow, cancellationToken ).ConfigureAwait( false );
2028 ············}
2029 ········}
2030
2031 ········async Task<IList> LoadRelationCoreAsync( IPersistenceCapable pc, Relation r, bool hollow, CancellationToken cancellationToken )
2032 ········{
2033 ············IList result = null;
2034
2035 ············if (pc.NDOObjectState == NDOObjectState.Created)
2036 ················return null;
2037
2038 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
2039 ················await LoadDataAsync( pc, cancellationToken ).ConfigureAwait( false );
2040
2041 ············if(r.MappingTable == null)
2042 ············{
2043 ················// 1:1 are loaded with LoadData
2044 ················if (r.Multiplicity == RelationMultiplicity.List)
2045 ················{
2046 ····················// Help GC by clearing lists
2047 ····················IList l = mappings.GetRelationContainer(pc, r);
2048 ····················if(l != null)
2049 ························l.Clear();
2050 ····················IList relatedObjects = await QueryRelatedObjectsAsync( pc, r, l, hollow, cancellationToken ).ConfigureAwait( false );
2051 ····················mappings.SetRelationContainer(pc, r, relatedObjects);
2052 ····················result = relatedObjects;
2053 ················}
2054 ············}
2055 ············else
2056 ············{
2057 ················DataTable dt = null;
2058
2059 ················using (IMappingTableHandler handler = PersistenceHandlerManager.GetPersistenceHandler( pc ).GetMappingTableHandler( r ))
2060 ················{
2061 ····················await CheckTransactionAsync( handler, r.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2062 ····················dt = await handler.FindRelatedObjectsAsync( pc.NDOObjectId, this.ds, cancellationToken ).ConfigureAwait( false );
2063 ················}
2064
2065 ················IList relatedObjects;
2066 ················if(r.Multiplicity == RelationMultiplicity.Element)
2067 ····················relatedObjects = GenericListReflector.CreateList(r.ReferencedType, dt.Rows.Count);
2068 ················else
2069 ················{
2070 ····················relatedObjects = mappings.GetRelationContainer(pc, r);
2071 ····················if(relatedObjects != null)
2072 ························relatedObjects.Clear();··// Objects will be reread
2073 ····················else
2074 ························relatedObjects = mappings.CreateRelationContainer(pc, r);
2075 ················}
2076 ····················
2077 ················foreach(DataRow objRow in dt.Rows)
2078 ················{
2079 ····················Type relType;
2080
2081 ····················if (r.MappingTable.ChildForeignKeyTypeColumnName != null)························
2082 ····················{
2083 ························object typeCodeObj = objRow[r.MappingTable.ChildForeignKeyTypeColumnName];
2084 ························if (typeCodeObj is System.DBNull)
2085 ····························throw new NDOException( 75, String.Format( "Can't resolve subclass type code of type {0} in relation '{1}' - the type code in the data row is null.", r.ReferencedTypeName, r.ToString() ) );
2086 ························relType = typeManager[(int)typeCodeObj];
2087 ························if (relType == null)
2088 ····························throw new NDOException(75, String.Format("Can't resolve subclass type code {0} of type {1} - check, if your NDOTypes.xml exists.", objRow[r.MappingTable.ChildForeignKeyTypeColumnName], r.ReferencedTypeName));
2089 ····················}························
2090 ····················else
2091 ····················{
2092 ························relType = r.ReferencedType;
2093 ····················}
2094
2095 ····················//TODO: Generic Types: Exctract the type description from the type name column
2096 ····················if (relType.IsGenericTypeDefinition)
2097 ························throw new NotImplementedException("NDO doesn't support relations to generic types via mapping tables.");
2098 ····················ObjectId id = ObjectIdFactory.NewObjectId(relType, GetClass(relType), objRow, r.MappingTable, this.typeManager);
2099 ····················IPersistenceCapable relObj = FindObject(id);
2100 ····················relatedObjects.Add(relObj);
2101 ················}····
2102 ················if (r.Multiplicity == RelationMultiplicity.Element)
2103 ················{
2104 ····················Debug.Assert(relatedObjects.Count <= 1, "NDO retrieved more than one object for relation with cardinality 1");
2105 ····················mappings.SetRelationField(pc, r.FieldName, relatedObjects.Count > 0 ? relatedObjects[0] : null);
2106 ················}
2107 ················else
2108 ················{
2109 ····················mappings.SetRelationContainer(pc, r, relatedObjects);
2110 ····················result = relatedObjects;
2111 ················}
2112 ············}
2113 ············// Mark relation as loaded
2114 ············pc.NDOSetLoadState(r.Ordinal, true);
2115 ············return result;
2116 ········}
2117
2118 ········/// <summary>
2119 ········/// Loads elements of a relation
2120 ········/// </summary>
2121 ········/// <param name="pc">The object which needs to load the relation</param>
2122 ········/// <param name="relationName">The name of the relation</param>
2123 ········/// <param name="hollow">Determines, if the related objects should be hollow.</param>
2124 ········internal IList LoadRelationInternal(IPersistenceCapable pc, string relationName, bool hollow)
2125 ········{
2126 ············return LoadRelationInternalAsync( pc, relationName, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
2127 ········}
2128
2129 ········internal async Task<IList> LoadRelationInternalAsync( IPersistenceCapable pc, string relationName, bool hollow, CancellationToken cancellationToken = default )
2130 ········{
2131 ············if (pc.NDOObjectState == NDOObjectState.Created)
2132 ················return null;
2133 ············Class cl = GetClass(pc);
2134
2135 ············Relation r = cl.FindRelation(relationName);
2136
2137 ············if ( r == null )
2138 ················throw new NDOException( 76, String.Format( "Error while loading related objects: Can't find relation mapping for the field {0}.{1}. Check your mapping file.", pc.GetType().FullName, relationName ) );
2139
2140 ············if ( pc.NDOGetLoadState( r.Ordinal ) )
2141 ················return null;
2142
2143 ············return await LoadRelationAsync( pc, r, hollow, cancellationToken ).ConfigureAwait( false );
2144 ········}
2145
2146 ········/// <summary>
2147 ········/// Load the related objects of a parent object. The current value of the relation is replaced by the
2148 ········/// a list of objects that has been read from the DB.
2149 ········/// </summary>
2150 ········/// <param name="pc">The parent object of the relations</param>
2151 ········/// <param name="row">A data row containing the state of the object</param>
2152 ········private void LoadRelated1To1Objects(IPersistenceCapable pc, DataRow row)
2153 ········{
2154 ············// Stripped down to only serve 1:1-Relations w/out mapping table
2155 ············Class cl = GetClass(pc);
2156 ············foreach(Relation r in cl.Relations)
2157 ············{
2158 ················if(r.MappingTable == null)
2159 ················{
2160 ····················if (r.Multiplicity == RelationMultiplicity.Element)
2161 ····················{
2162 ························bool isNull = false;
2163 ························foreach (ForeignKeyColumn fkColumn in r.ForeignKeyColumns)
2164 ························{
2165 ····························isNull = isNull || (row[fkColumn.Name] == DBNull.Value);
2166 ························}
2167 ························if (isNull)
2168 ························{
2169 ····························mappings.SetRelationField(pc, r.FieldName, null);
2170 ························}
2171 ························else
2172 ························{
2173 ····························Type relType;
2174 ····························if (r.HasSubclasses)
2175 ····························{
2176 ································object o = row[r.ForeignKeyTypeColumnName];
2177 ································if (o == DBNull.Value)
2178 ····································throw new NDOException(75, String.Format(
2179 ········································"Can't resolve subclass type code {0} of type {1} - type code value is DBNull.",
2180 ········································row[r.ForeignKeyTypeColumnName], r.ReferencedTypeName));
2181 ································relType = typeManager[(int)o];
2182 ····························}
2183 ····························else
2184 ····························{
2185 ································relType = r.ReferencedType;
2186 ····························}
2187 ····························if (relType == null)
2188 ····························{
2189 ································throw new NDOException(75, String.Format(
2190 ····································"Can't resolve subclass type code {0} of type {1} - check, if your mapping file is correct.",
2191 ····································row[r.ForeignKeyTypeColumnName], r.ReferencedTypeName));
2192 ····························}
2193 ····
2194 ····························int count = r.ForeignKeyColumns.Count();
2195 ····························object[] keydata = new object[count];
2196 ····························int i = 0;
2197 ····························foreach(ForeignKeyColumn fkColumn in r.ForeignKeyColumns)
2198 ····························{
2199 ································keydata[i++] = row[fkColumn.Name];
2200 ····························}
2201
2202 ····························Type oidType = relType;
2203 ····························if (oidType.IsGenericTypeDefinition)
2204 ································oidType = mappings.GetRelationFieldType(r);
2205
2206 ····························ObjectId childOid = ObjectIdFactory.NewObjectId(oidType, GetClass(relType), keydata, this.typeManager);
2207 ····························if(childOid.IsValid())
2208 ································mappings.SetRelationField(pc, r.FieldName, FindObject(childOid));
2209 ····························else
2210 ································mappings.SetRelationField(pc, r.FieldName, null);
2211
2212 ························}
2213 ························pc.NDOSetLoadState(r.Ordinal, true);
2214 ····················}
2215 ················}
2216 ············}
2217 ········}
2218
2219 ········
2220 ········/// <summary>
2221 ········/// Creates a new ObjectId with the same Key value as a given ObjectId.
2222 ········/// </summary>
2223 ········/// <param name="oid">An ObjectId, which Key value will be used to build the new ObjectId.</param>
2224 ········/// <param name="t">The type of the object, the id will belong to.</param>
2225 ········/// <returns>An object of type ObjectId, or ObjectId.InvalidId</returns>
2226 ········/// <remarks>If the type t doesn't have a mapping in the mapping file an Exception of type NDOException is thrown.</remarks>
2227 ········public ObjectId NewObjectId(ObjectId oid, Type t)
2228 ········{
2229 ············return new ObjectId(oid.Id, t);
2230 ········}
2231
2232 ········/*
2233 ········/// <summary>
2234 ········/// Creates a new ObjectId which can be used to retrieve objects from the database.
2235 ········/// </summary>
2236 ········/// <param name="keyData">The id, which will be used to search for the object in the database</param>
2237 ········/// <param name="t">The type of the object.</param>
2238 ········/// <returns>An object of type ObjectId, or ObjectId.InvalidId</returns>
2239 ········/// <remarks>The keyData parameter must be one of the types Int32, String, Byte[] or Guid. If keyData is null or the type of keyData is invalid the function returns ObjectId.InvalidId. If the type t doesn't have a mapping in the mapping file, an Exception of type NDOException is thrown.</remarks>
2240 ········public ObjectId NewObjectId(object keyData, Type t)
2241 ········{
2242 ············if (keyData == null || keyData == DBNull.Value)
2243 ················return ObjectId.InvalidId;
2244
2245 ············Class cl =··GetClass(t);············
2246 ············
2247 ············if (cl.Oid.FieldType == typeof(int))
2248 ················return new ObjectId(new Int32Key(t, (int)keyData));
2249 ············else if (cl.Oid.FieldType == typeof(string))
2250 ················return new ObjectId(new StringKey(t, (String) keyData));
2251 ············else if (cl.Oid.FieldType == typeof(Guid))
2252 ················if (keyData is string)
2253 ····················return new ObjectId(new GuidKey(t, new Guid((String) keyData)));
2254 ················else
2255 ····················return new ObjectId(new GuidKey(t, (Guid) keyData));
2256 ············else if (cl.Oid.FieldType == typeof(MultiKey))
2257 ················return new ObjectId(new MultiKey(t, (object[]) keyData));
2258 ············else
2259 ················return ObjectId.InvalidId;
2260 ········}
2261 ········*/
2262
2263
2264 ········/*
2265 ········ * ····················if (cl.Oid.FieldName != null && HasOwnerCreatedIds)
2266 ····················{
2267 ························// The column, which hold the oid gets overwritten, if
2268 ························// Oid.FieldName contains a value.
2269 */
2270 ········private void WriteIdFieldsToRow(IPersistenceCapable pc, DataRow row)
2271 ········{
2272 ············Class cl = GetClass(pc);
2273
2274 ············if (cl.Oid.IsDependent)
2275 ················return;
2276
2277 ············Key key = pc.NDOObjectId.Id;
2278
2279 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2280 ············{
2281 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2282 ················if (oidColumn.FieldName != null)
2283 ················{
2284 ····················row[oidColumn.Name] = key[i];
2285 ················}
2286 ············}
2287 ········}
2288
2289 ········private void WriteIdToRow(IPersistenceCapable pc, DataRow row)
2290 ········{
2291 ············NDO.Mapping.Class cl = GetClass(pc);
2292 ············ObjectId oid = pc.NDOObjectId;
2293
2294 ············if (cl.TimeStampColumn != null)
2295 ················row[cl.TimeStampColumn] = pc.NDOTimeStamp;
2296
2297 ············if (cl.Oid.IsDependent)··// Oid data is in relation columns
2298 ················return;
2299
2300 ············Key key = oid.Id;
2301
2302 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2303 ············{
2304 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2305 ················row[oidColumn.Name] = key[i];
2306 ············}
2307 ········}
2308
2309 ········private void ReadIdFromRow(IPersistenceCapable pc, DataRow row)
2310 ········{
2311 ············ObjectId oid = pc.NDOObjectId;
2312 ············NDO.Mapping.Class cl = GetClass(pc);
2313
2314 ············if (cl.Oid.IsDependent)··// Oid data is in relation columns
2315 ················return;
2316
2317 ············Key key = oid.Id;
2318
2319 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2320 ············{
2321 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2322 ················object o = row[oidColumn.Name];
2323 ················if (!(o is Int32) && !(o is Guid) && !(o is String) && !(o is Int64))
2324 ····················throw new NDOException(78, "ReadId: invalid Id Column type in " + oidColumn.Name + ": " + o.GetType().FullName);
2325 ················if (oidColumn.SystemType == typeof(Guid) && (o is String))
2326 ····················key[i] = new Guid((string)o);
2327 ················else
2328 ····················key[i] = o;
2329 ············}
2330
2331 ········}
2332
2333 ········private void ReadId (Cache.Entry e)
2334 ········{
2335 ············ReadIdFromRow(e.pc, e.row);
2336 ········}
2337
2338 ········private void WriteObject(IPersistenceCapable pc, DataRow row, string[] fieldNames)
2339 ········{
2340 ············WriteObject(pc, row, fieldNames, 0);
2341 ········}
2342
2343 ········private void ReadTimeStamp(Class cl, IPersistenceCapable pc, DataRow row)
2344 ········{
2345 ············if (cl.TimeStampColumn == null)
2346 ················return;
2347 ············object col = row[cl.TimeStampColumn];
2348 ············if (col is String)
2349 ················pc.NDOTimeStamp = new Guid(col.ToString());
2350 ············else
2351 ················pc.NDOTimeStamp = (Guid) col;
2352 ········}
2353
2354
2355
2356 ········private void ReadTimeStamp(Cache.Entry e)
2357 ········{
2358 ············IPersistenceCapable pc = e.pc;
2359 ············NDO.Mapping.Class cl = GetClass(pc);
2360 ············Debug.Assert(!IsFakeRow(cl, e.row));
2361 ············if (cl.TimeStampColumn == null)
2362 ················return;
2363 ············if (e.row[cl.TimeStampColumn] is String)
2364 ················e.pc.NDOTimeStamp = new Guid(e.row[cl.TimeStampColumn].ToString());
2365 ············else
2366 ················e.pc.NDOTimeStamp = (Guid) e.row[cl.TimeStampColumn];
2367 ········}
2368
2369 ········/// <summary>
2370 ········/// Determines, if any objects are new, changed or deleted.
2371 ········/// </summary>
2372 ········public virtual bool HasChanges
2373 ········{
2374 ············get
2375 ············{
2376 ················return cache.LockedObjects.Count > 0;
2377 ············}
2378 ········}
2379
2380 ········/// <summary>
2381 ········/// Do the update for all rows in the ds.
2382 ········/// </summary>
2383 ········/// <param name="types">Types with changes.</param>
2384 ········/// <param name="delete">True, if delete operations are to be performed.</param>
2385 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2386 ········/// <remarks>
2387 ········/// Delete and Insert/Update operations are to be separated to maintain the type order.
2388 ········/// </remarks>
2389 ········private async Task UpdateTypesAsync( IList types, bool delete, CancellationToken cancellationToken )
2390 ········{
2391 ············foreach(Type t in types)
2392 ············{
2393 ················//Debug.WriteLine("Update Deleted Objects: "··+ t.Name);
2394 ················using (IPersistenceHandler handler = PersistenceHandlerManager.GetPersistenceHandler( t ))
2395 ················{
2396 ····················await CheckTransactionAsync( handler, t, cancellationToken ).ConfigureAwait( false );
2397 ····················ConcurrencyErrorHandler ceh = new ConcurrencyErrorHandler(this.OnConcurrencyError);
2398 ····················handler.ConcurrencyError += ceh;
2399 ····················try
2400 ····················{
2401 ························DataTable dt = GetTable(t);
2402 ························if (delete)
2403 ····························await handler.UpdateDeletedObjectsAsync( dt, cancellationToken ).ConfigureAwait( false );
2404 ························else
2405 ····························await handler.UpdateAsync( dt, cancellationToken ).ConfigureAwait( false );
2406 ····················}
2407 ····················finally
2408 ····················{
2409 ························handler.ConcurrencyError -= ceh;
2410 ····················}
2411 ················}
2412 ············}
2413 ········}
2414
2415 ········internal async Task UpdateCreatedMappingTableEntriesAsync( CancellationToken cancellationToken )
2416 ········{
2417 ············foreach (MappingTableEntry e in createdMappingTableObjects)
2418 ············{
2419 ················if (!e.DeleteEntry)
2420 ····················WriteMappingTableEntry(e);
2421 ············}
2422 ············// Now update all mapping tables
2423 ············foreach (IMappingTableHandler handler in mappingHandler.Values)
2424 ············{
2425 ················await CheckTransactionAsync( handler, handler.Relation.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2426 ················await handler.UpdateAsync( ds, cancellationToken ).ConfigureAwait( false );
2427 ············}
2428 ········}
2429
2430 ········internal async Task UpdateDeletedMappingTableEntriesAsync( CancellationToken cancellationToken )
2431 ········{
2432 ············foreach (MappingTableEntry e in createdMappingTableObjects)
2433 ············{
2434 ················if (e.DeleteEntry)
2435 ····················WriteMappingTableEntry(e);
2436 ············}
2437 ············// Now update all mapping tables
2438 ············foreach (IMappingTableHandler handler in mappingHandler.Values)
2439 ············{
2440 ················await CheckTransactionAsync( handler, handler.Relation.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2441 ················await handler.UpdateAsync( ds, cancellationToken ).ConfigureAwait( false );
2442 ············}
2443 ········}
2444
2445 ········/// <summary>
2446 ········/// Save all changed object into the DataSet and update the DB.
2447 ········/// When a newly created object is written to DB, the key might change. Therefore,
2448 ········/// the id is updated and the object is removed and re-inserted into the cache.
2449 ········/// </summary>
2450 ········public void Save(bool deferCommit = false)
2451 ········{
2452 ············SaveAsync( deferCommit ).ConfigureAwait( false ).GetAwaiter().GetResult();
2453 ········}
2454
2455 ········/// <summary>
2456 ········/// Save all changed object into the DataSet and update the DB asynchronously.
2457 ········/// When a newly created object is written to DB, the key might change. Therefore,
2458 ········/// the id is updated and the object is removed and re-inserted into the cache.
2459 ········/// </summary>
2460 ········/// <param name="deferCommit">Determines, if the commit of the transaction should be deferred.</param>
2461 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2462 ········/// <remarks>
2463 ········/// User callbacks like CollisionEvent and OnSavedEvent might be called on a thread pool thread.
2464 ········/// </remarks>
2465 ········public virtual async Task SaveAsync( bool deferCommit = false, CancellationToken cancellationToken = default )
2466 ········{
2467 ············using (EnterOperation())
2468 ············{
2469 ················await SaveInternalAsync( deferCommit, cancellationToken ).ConfigureAwait( false );
2470 ············}
2471 ········}
2472
2473 ········async Task SaveInternalAsync( bool deferCommit, CancellationToken cancellationToken )
2474 ········{
2475 ············if (IsClosed)
2476 ················throw new ObjectDisposedException(GetType().Name);
2477
2478 ············this.DeferredMode = deferCommit;
2479 ············var htOnSaving = new HashSet<ObjectId>();
2480 ············for(;;)
2481 ············{
2482 ················// We need to work on a copy of the locked objects list,
2483 ················// since the handlers might add more objects to the cache
2484 ················var lockedObjects = cache.LockedObjects.ToList();
2485 ················int count = lockedObjects.Count;
2486 ················foreach(Cache.Entry e in lockedObjects)
2487 ················{
2488 ····················if (e.pc.NDOObjectState != NDOObjectState.Deleted)
2489 ····················{
2490 ························IPersistenceNotifiable ipn = e.pc as IPersistenceNotifiable;
2491 ························if (ipn != null)
2492 ························{
2493 ····························if (!htOnSaving.Contains(e.pc.NDOObjectId))
2494 ····························{
2495 ································ipn.OnSaving();
2496 ································htOnSaving.Add(e.pc.NDOObjectId);
2497 ····························}
2498 ························}
2499 ····················}
2500 ················}
2501 ················// The system is stable, if the count doesn't change
2502 ················if (cache.LockedObjects.Count == count)
2503 ····················break;
2504 ············}
2505
2506 ············if (this.OnSavingEvent != null)
2507 ············{
2508 ················IList onSavingObjects = new ArrayList(cache.LockedObjects.Count);
2509 ················foreach(Cache.Entry e in cache.LockedObjects)
2510 ····················onSavingObjects.Add(e.pc);
2511 ················OnSavingEvent(onSavingObjects);
2512 ············}
2513
2514 ············List<Type> types = new List<Type>();
2515 ············List<IPersistenceCapable> deletedObjects = new List<IPersistenceCapable>();
2516 ············List<IPersistenceCapable> hollowModeObjects = hollowMode ? new List<IPersistenceCapable>() : null;
2517 ············List<IPersistenceCapable> changedObjects = new List<IPersistenceCapable>();
2518 ············List<IPersistenceCapable> addedObjects = new List<IPersistenceCapable>();
2519 ············List<Cache.Entry> addedCacheEntries = new List<Cache.Entry>();
2520
2521 ············// Save current state in DataSet
2522 ············foreach (Cache.Entry e in cache.LockedObjects)
2523 ············{
2524 ················Type objType = e.pc.GetType();
2525
2526 ················if (objType.IsGenericType && !objType.IsGenericTypeDefinition)
2527 ····················objType = objType.GetGenericTypeDefinition();
2528
2529 ················Class cl = GetClass(e.pc);
2530 ················//Debug.WriteLine("Saving: " + objType.Name + " id = " + e.pc.NDOObjectId.Dump());
2531 ················if(!types.Contains(objType))
2532 ················{
2533 ····················//Debug.WriteLine("Added··type " + objType.Name);
2534 ····················types.Add(objType);
2535 ················}
2536 ················NDOObjectState objectState = e.pc.NDOObjectState;
2537 ················if(objectState == NDOObjectState.Deleted)
2538 ················{
2539 ····················deletedObjects.Add(e.pc);
2540 ················}
2541 ················else if(objectState == NDOObjectState.Created)
2542 ················{
2543 ····················WriteObject(e.pc, e.row, cl.ColumnNames);····················
2544 ····················WriteIdFieldsToRow(e.pc, e.row);··// If fields are mapped to Oid, write them into the row
2545 ····················WriteForeignKeysToRow(e.pc, e.row);
2546 ····················//····················Debug.WriteLine(e.pc.GetType().FullName);
2547 ····················//····················DataRow[] rows = new DataRow[cache.LockedObjects.Count];
2548 ····················//····················i = 0;
2549 ····················//····················foreach(Cache.Entry e2 in cache.LockedObjects)
2550 ····················//····················{
2551 ····················//························rows[i++] = e2.row;
2552 ····················//····················}
2553 ····················//····················System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("testCommand");
2554 ····················//····················new SqlDumper(new DebugLogAdapter(), NDOProviderFactory.Instance["Sql"], cmd, cmd, cmd, cmd).Dump(rows);
2555
2556 ····················addedCacheEntries.Add(e);
2557 ····················addedObjects.Add( e.pc );
2558 ····················//····················objectState = NDOObjectState.Persistent;
2559 ················}
2560 ················else
2561 ················{
2562 ····················if (e.pc.NDOObjectState == NDOObjectState.PersistentDirty)
2563 ························changedObjects.Add( e.pc );
2564 ····················WriteObject(e.pc, e.row, cl.ColumnNames);
2565 ····················WriteForeignKeysToRow(e.pc, e.row); ····················
2566 ················}
2567 ················if(hollowMode && (objectState == NDOObjectState.Persistent || objectState == NDOObjectState.Created || objectState == NDOObjectState.PersistentDirty) )
2568 ················{
2569 ····················hollowModeObjects.Add(e.pc);
2570 ················}
2571 ············}
2572
2573 ············// Before we delete any db rows, we have to make sure, to delete mapping
2574 ············// table entries first, which might have relations to the db rows to be deleted
2575 ············await UpdateDeletedMappingTableEntriesAsync( cancellationToken ).ConfigureAwait( false );
2576
2577 ············// Update DB
2578 ············if (ds.HasChanges())
2579 ············{
2580
2581 ················// We need the reversed update order for deletions.
2582 ················types.Sort( ( t1, t2 ) =>
2583 ················{
2584 ····················int i1 = mappings.GetUpdateOrder( t1 );
2585 ····················int i2 = mappings.GetUpdateOrder( t2 );
2586 ····················if (i1 < i2)
2587 ····················{
2588 ························if (!addedObjects.Any( pc => pc.GetType() == t1 ))
2589 ····························i1 += 100000;
2590 ····················}
2591 ····················else
2592 ····················{
2593 ························if (!addedObjects.Any( pc => pc.GetType() == t2 ))
2594 ····························i2 += 100000;
2595 ····················}
2596 ····················return i2 - i1;
2597 ················} );
2598
2599 ················// Delete records first
2600
2601 ················await UpdateTypesAsync( types, true, cancellationToken ).ConfigureAwait( false );
2602
2603 ················// Now do all other updates in correct order.
2604 ················types.Reverse();
2605
2606 ················await UpdateTypesAsync( types, false, cancellationToken ).ConfigureAwait( false );
2607 ················
2608 ················ds.AcceptChanges();
2609 ················if(createdDirectObjects.Count > 0)
2610 ················{
2611 ····················// Rewrite all children that have foreign keys to parents which have just been saved now.
2612 ····················// They must be written again to store the correct foreign keys.
2613 ····················foreach(IPersistenceCapable pc in createdDirectObjects)
2614 ····················{
2615 ························Class cl = GetClass(pc);
2616 ························DataRow r = this.cache.GetDataRow(pc);
2617 ························string fakeColumnName = GetFakeRowOidColumnName(cl);
2618 ························object o = r[fakeColumnName];
2619 ························r[fakeColumnName] = o;
2620 ····················}
2621
2622 ····················await UpdateTypesAsync( types, false, cancellationToken ).ConfigureAwait( false );
2623 ················}
2624
2625 ················// Because object id might have changed during DB insertion, re-register newly created objects in the cache.
2626 ················foreach(Cache.Entry e in addedCacheEntries)
2627 ················{
2628 ····················cache.DeregisterLockedObject(e.pc);
2629 ····················ReadId(e);
2630 ····················cache.RegisterLockedObject(e.pc, e.row, e.relations);
2631 ················}
2632
2633 ················// Now update all mapping tables. Because of possible subclasses, there is no
2634 ················// relation between keys in the dataset schema. Therefore, we can update mapping
2635 ················// tables only after all other objects have been written to ensure correct foreign keys.
2636 ················await UpdateCreatedMappingTableEntriesAsync( cancellationToken ).ConfigureAwait( false );
2637
2638 ················// The rows may contain now new Ids, which should be
2639 ················// stored in the lostRowInfo's before the rows get detached
2640 ················foreach(Cache.Entry e in cache.LockedObjects)
2641 ················{
2642 ····················if (e.row.RowState != DataRowState.Detached)
2643 ····················{
2644 ························IPersistenceCapable pc = e.pc;
2645 ························ReadLostForeignKeysFromRow(GetClass(pc), pc, e.row);
2646 ····················}
2647 ················}
2648
2649 ················ds.AcceptChanges();
2650 ············}
2651
2652 ············await EndSaveAsync( !deferCommit, cancellationToken ).ConfigureAwait( false );
2653
2654 ············foreach(IPersistenceCapable pc in deletedObjects)
2655 ············{
2656 ················MakeObjectTransient(pc, false);
2657 ············}
2658
2659 ············ds.Clear();
2660 ············mappingHandler.Clear();
2661 ············createdDirectObjects.Clear();
2662 ············createdMappingTableObjects.Clear();
2663 ············this.relationChanges.Clear();
2664
2665 ············if(hollowMode)
2666 ············{
2667 ················MakeHollow(hollowModeObjects);
2668 ············}
2669
2670 ············if (this.OnSavedEvent != null)
2671 ············{
2672 ················AuditSet auditSet = new AuditSet()
2673 ················{
2674 ····················ChangedObjects = changedObjects,
2675 ····················CreatedObjects = addedObjects,
2676 ····················DeletedObjects = deletedObjects
2677 ················};
2678 ················this.OnSavedEvent( auditSet );
2679 ············}
2680 ········}
2681
2682 ········private async Task EndSaveAsync( bool forceCommit, CancellationToken cancellationToken )
2683 ········{
2684 ············foreach(Cache.Entry e in cache.LockedObjects)
2685 ············{
2686 ················if (e.pc.NDOObjectState == NDOObjectState.Created || e.pc.NDOObjectState == NDOObjectState.PersistentDirty)
2687 ····················this.ReadTimeStamp(e);
2688 ················e.pc.NDOObjectState = NDOObjectState.Persistent;
2689 ············}
2690
2691 ············cache.UnlockAll();
2692
2693 ············await CheckEndTransactionAsync( forceCommit, cancellationToken ).ConfigureAwait( false );
2694 ········}
2695
2696 ········/// <summary>
2697 ········/// Write all foreign keys for 1:1-relations.
2698 ········/// </summary>
2699 ········/// <param name="pc">The persistent object.</param>
2700 ········/// <param name="pcRow">The DataRow of the pesistent object.</param>
2701 ········private void WriteForeignKeysToRow(IPersistenceCapable pc, DataRow pcRow)
2702 ········{
2703 ············foreach(Relation r in mappings.Get1to1Relations(pc.GetType()))
2704 ············{
2705 ················IPersistenceCapable relObj = (IPersistenceCapable)mappings.GetRelationField(pc, r.FieldName);
2706 ················bool isDependent = GetClass(pc).Oid.IsDependent;
2707
2708 ················if ( relObj != null )
2709 ················{
2710 ····················int i = 0;
2711 ····················foreach ( ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2712 ····················{
2713 ························pcRow[fkColumn.Name] = relObj.NDOObjectId.Id[i++];
2714 ····················}
2715 ····················if ( r.ForeignKeyTypeColumnName != null )
2716 ····················{
2717 ························pcRow[r.ForeignKeyTypeColumnName] = relObj.NDOObjectId.Id.TypeId;
2718 ····················}
2719 ················}
2720 ················else
2721 ················{
2722 ····················foreach ( ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2723 ····················{
2724 ························pcRow[fkColumn.Name] = DBNull.Value;
2725 ····················}
2726 ····················if ( r.ForeignKeyTypeColumnName != null )
2727 ····················{
2728 ························pcRow[r.ForeignKeyTypeColumnName] = DBNull.Value;
2729 ····················}
2730 ················}
2731 ············}
2732 ········}
2733
2734
2735
2736 ········/// <summary>
2737 ········/// Write a mapping table entry to it's corresponding table. This is a pair of foreign keys.
2738 ········/// </summary>
2739 ········/// <param name="e">the mapping table entry</param>
2740 ········private void WriteMappingTableEntry(MappingTableEntry e)
2741 ········{
2742 ············IPersistenceCapable pc = e.ParentObject;
2743 ············IPersistenceCapable relObj = e.RelatedObject;
2744 ············Relation r = e.Relation;
2745 ············DataTable dt = GetTable(r.MappingTable.TableName);
2746 ············DataRow row = dt.NewRow();
2747 ············int i = 0;
2748 ············foreach (ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2749 ············{
2750 ················row[fkColumn.Name] = pc.NDOObjectId.Id[i++];
2751 ············}
2752 ············i = 0;
2753 ············foreach (ForeignKeyColumn fkColumn in r.MappingTable.ChildForeignKeyColumns)
2754 ············{
2755 ················row[fkColumn.Name] = relObj.NDOObjectId.Id[i++];
2756 ············}
2757
2758 ············if (r.ForeignKeyTypeColumnName != null)
2759 ················row[r.ForeignKeyTypeColumnName] = pc.NDOObjectId.Id.TypeId;
2760 ············if (r.MappingTable.ChildForeignKeyTypeColumnName != null)
2761 ················row[r.MappingTable.ChildForeignKeyTypeColumnName] = relObj.NDOObjectId.Id.TypeId;
2762
2763 ············dt.Rows.Add(row);
2764 ············if(e.DeleteEntry)
2765 ············{
2766 ················row.AcceptChanges();
2767 ················row.Delete();
2768 ············}
2769
2770 ············IMappingTableHandler handler;
2771 ············if (!mappingHandler.TryGetValue( r, out handler ))
2772 ············{
2773 ················mappingHandler[r] = handler = PersistenceHandlerManager.GetPersistenceHandler( pc ).GetMappingTableHandler( r );
2774 ············}
2775 ········}
2776
2777
2778 ········/// <summary>
2779 ········/// Undo changes of a certain object
2780 ········/// </summary>
2781 ········/// <param name="o">Object to undo</param>
2782 ········public void Restore(object o)
2783 ········{············
2784 ············IPersistenceCapable pc = CheckPc(o);
2785 ············Cache.Entry e = null;
2786 ············foreach (Cache.Entry entry in cache.LockedObjects)
2787 ············{
2788 ················if (entry.pc == pc)
2789 ················{
2790 ····················e = entry;
2791 ····················break;
2792 ················}
2793 ············}
2794 ············if (e == null)
2795 ················return;
2796 ············Class cl = GetClass(e.pc);
2797 ············switch (pc.NDOObjectState)
2798 ············{
2799 ················case NDOObjectState.PersistentDirty:
2800 ····················ObjectListManipulator.Remove(createdDirectObjects, pc);
2801 ····················foreach(Relation r in cl.Relations)
2802 ····················{
2803 ························if (r.Multiplicity == RelationMultiplicity.Element)
2804 ························{
2805 ····························IPersistenceCapable subPc = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
2806 ····························if (subPc != null && cache.IsLocked(subPc))
2807 ································Restore(subPc);
2808 ························}
2809 ························else
2810 ························{
2811 ····························if (!pc.NDOGetLoadState(r.Ordinal))
2812 ································continue;
2813 ····························IList subList = (IList) mappings.GetRelationContainer(pc, r);
2814 ····························if (subList != null)
2815 ····························{
2816 ································foreach(IPersistenceCapable subPc2 in subList)
2817 ································{
2818 ····································if (cache.IsLocked(subPc2))
2819 ········································Restore(subPc2);
2820 ································}
2821 ····························}
2822 ························}
2823 ····················}
2824 ····················RestoreRelatedObjects(pc, e.relations);
2825 ····················e.row.RejectChanges();
2826 ····················ReadObject(pc, e.row, cl.ColumnNames, 0);
2827 ····················cache.Unlock(pc);
2828 ····················pc.NDOObjectState = NDOObjectState.Persistent;
2829 ····················break;
2830 ················case NDOObjectState.Created:
2831 ····················ReadObject(pc, e.row, cl.ColumnNames, 0);
2832 ····················cache.Unlock(pc);
2833 ····················MakeObjectTransient(pc, true);
2834 ····················break;
2835 ················case NDOObjectState.Deleted:
2836 ····················if (!this.IsFakeRow(cl, e.row))
2837 ····················{
2838 ························e.row.RejectChanges();
2839 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2840 ························e.pc.NDOObjectState = NDOObjectState.Persistent;
2841 ····················}
2842 ····················else
2843 ····················{
2844 ························e.row.RejectChanges();
2845 ························e.pc.NDOObjectState = NDOObjectState.Hollow;
2846 ····················}
2847 ····················cache.Unlock(pc);
2848 ····················break;
2849
2850 ············}
2851 ········}
2852
2853 ········/// <summary>
2854 ········/// Aborts a pending transaction without restoring the object state.
2855 ········/// </summary>
2856 ········/// <remarks>Supports both local and EnterpriseService Transactions.</remarks>
2857 ········public void AbortTransaction()
2858 ········{
2859 ············AbortTransactionAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
2860 ········}
2861
2862 ········/// <summary>
2863 ········/// Aborts a pending transaction asynchronously without restoring the object state.
2864 ········/// </summary>
2865 ········/// <remarks>The rollback can't be canceled, therefore there is no CancellationToken.</remarks>
2866 ········public virtual async Task AbortTransactionAsync()
2867 ········{
2868 ············await TransactionScope.DisposeAsync().ConfigureAwait( false );
2869 ········}
2870
2871 ········/// <summary>
2872 ········/// Rejects all changes and restores the original object state. Added Objects will be made transient.
2873 ········/// </summary>
2874 ········public void Abort()
2875 ········{
2876 ············AbortAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
2877 ········}
2878
2879 ········/// <summary>
2880 ········/// Rejects all changes and restores the original object state asynchronously. Added Objects will be made transient.
2881 ········/// </summary>
2882 ········/// <remarks>The rollback can't be canceled, therefore there is no CancellationToken.</remarks>
2883 ········public virtual async Task AbortAsync()
2884 ········{
2885 ············// RejectChanges of the DS cannot be called because newly added rows would be deleted,
2886 ············// and therefore, couldn't be restored. Instead we call RejectChanges() for each
2887 ············// individual row.
2888 ············createdDirectObjects.Clear();
2889 ············createdMappingTableObjects.Clear();
2890 ············ArrayList deletedObjects = new ArrayList();
2891 ············ArrayList hollowModeObjects = hollowMode ? new ArrayList() : null;
2892
2893 ············// Read all objects from DataSet
2894 ············foreach (Cache.Entry e in cache.LockedObjects)
2895 ············{
2896 ················//Debug.WriteLine("Reading: " + e.pc.GetType().Name);
2897
2898 ················Class cl = GetClass(e.pc);
2899 ················bool isFakeRow = this.IsFakeRow(cl, e.row);
2900 ················if (!isFakeRow)
2901 ················{
2902 ····················RestoreRelatedObjects(e.pc, e.relations);
2903 ················}
2904 ················else
2905 ················{
2906 ····················Debug.Assert(e.pc.NDOObjectState == NDOObjectState.Deleted, "Fake row objects can only exist in deleted state");
2907 ················}
2908
2909 ················switch(e.pc.NDOObjectState)
2910 ················{
2911 ····················case NDOObjectState.Created:
2912 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2913 ························deletedObjects.Add(e.pc);
2914 ························break;
2915
2916 ····················case NDOObjectState.PersistentDirty:
2917 ························e.row.RejectChanges();
2918 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2919 ························e.pc.NDOObjectState = NDOObjectState.Persistent;
2920 ························break;
2921
2922 ····················case NDOObjectState.Deleted:
2923 ························if (!isFakeRow)
2924 ························{
2925 ····························e.row.RejectChanges();
2926 ····························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2927 ····························e.pc.NDOObjectState = NDOObjectState.Persistent;
2928 ························}
2929 ························else
2930 ························{
2931 ····························e.row.RejectChanges();
2932 ····························e.pc.NDOObjectState = NDOObjectState.Hollow;
2933 ························}
2934 ························break;
2935
2936 ····················default:
2937 ························throw new InternalException(2082, "Abort(): wrong state detected: " + e.pc.NDOObjectState + " id = " + e.pc.NDOObjectId.Dump());
2938 ························//Debug.Assert(false, "Object with wrong state detected: " + e.pc.NDOObjectState);
2939 ························//break;
2940 ················}
2941 ················if(hollowMode && e.pc.NDOObjectState == NDOObjectState.Persistent)
2942 ················{
2943 ····················hollowModeObjects.Add(e.pc);
2944 ················}
2945 ············}
2946 ············cache.UnlockAll();
2947 ············foreach(IPersistenceCapable pc in deletedObjects)
2948 ············{
2949 ················MakeObjectTransient(pc, true);
2950 ············}
2951 ············ds.Clear();
2952 ············mappingHandler.Clear();
2953 ············if(hollowMode)
2954 ············{
2955 ················MakeHollow(hollowModeObjects);
2956 ············}
2957
2958 ············this.relationChanges.Clear();
2959
2960
2961 ············await AbortTransactionAsync().ConfigureAwait( false );
2962 ········}
2963
2964
2965 ········/// <summary>
2966 ········/// Reset object to its transient state and remove it from the cache. Optinally, remove the object id to
2967 ········/// disable future access.
2968 ········/// </summary>
2969 ········/// <param name="pc"></param>
2970 ········/// <param name="removeId">Indicates if the object id should be nulled</param>
2971 ········private void MakeObjectTransient(IPersistenceCapable pc, bool removeId)
2972 ········{
2973 ············cache.Deregister(pc);
2974 ············// MakeTransient doesn't remove the ID, because delete makes objects transient and we need the id for the ChangeLog············
2975 ············if(removeId)
2976 ············{
2977 ················pc.NDOObjectId = null;
2978 ············}
2979 ············pc.NDOObjectState = NDOObjectState.Transient;
2980 ············pc.NDOStateManager = null;
2981 ········}
2982
2983 ········/// <summary>
2984 ········/// Makes an object transient.
2985 ········/// The object can be used afterwards, but changes will not be saved in the database.
2986 ········/// </summary>
2987 ········/// <remarks>
2988 ········/// Only persistent or hollow objects can be detached. Hollow objects are loaded to ensure valid data.
2989 ········/// </remarks>
2990 ········/// <param name="o">The object to detach.</param>
2991 ········public void MakeTransient(object o)
2992 ········{
2993 ············IPersistenceCapable pc = CheckPc(o);
2994 ············if(pc.NDOObjectState != NDOObjectState.Persistent && pc.NDOObjectState··!= NDOObjectState.Hollow)
2995 ············{
2996 ················throw new NDOException(79, "MakeTransient: Illegal state '" + pc.NDOObjectState + "' for this operation");
2997 ············}
2998
2999 ············if(pc.NDOObjectState··== NDOObjectState.Hollow)
3000 ············{
3001 ················LoadData(pc);
3002 ············}
3003 ············MakeObjectTransient(pc, true);
3004 ········}
3005
3006
3007 ········/// <summary>
3008 ········/// Make all objects of a list transient.
3009 ········/// </summary>
3010 ········/// <param name="list">the list of transient objects</param>
3011 ········public void MakeTransient(System.Collections.IList list)
3012 ········{
3013 ············foreach (IPersistenceCapable pc in list)
3014 ················MakeTransient(pc);
3015 ········}
3016
3017 ········/// <summary>
3018 ········/// Remove an object from the DB. Note that the object itself is not destroyed and may still be used.
3019 ········/// </summary>
3020 ········/// <param name="o">The object to remove</param>
3021 ········public void Delete(object o)
3022 ········{
3023 ············IPersistenceCapable pc = CheckPc(o);
3024 ············if (pc.NDOObjectState == NDOObjectState.Transient)
3025 ············{
3026 ················throw new NDOException( 120, "Can't delete transient object" );
3027 ············}
3028 ············if (pc.NDOObjectState != NDOObjectState.Deleted)
3029 ············{
3030 ················Delete(pc, true);
3031 ············}
3032 ········}
3033
3034
3035 ········private void LoadAllRelations(object o)
3036 ········{
3037 ············IPersistenceCapable pc = CheckPc(o);
3038 ············Class cl = GetClass(pc);
3039 ············foreach(Relation r in cl.Relations)
3040 ············{
3041 ················if (!pc.NDOGetLoadState(r.Ordinal))
3042 ····················LoadRelation(pc, r, true);
3043 ············}
3044 ········}
3045
3046
3047 ········/// <summary>
3048 ········/// Remove an object from the DB. Note that the object itself is not destroyed and may still be used.
3049 ········/// </summary>
3050 ········/// <remarks>
3051 ········/// If checkAssoziations it true, the object cannot be deleted if it is part of a bidirectional assoziation.
3052 ········/// This is the case if delete was called from user code. Internally, an object may be deleted because it is called from
3053 ········/// the parent object.
3054 ········/// </remarks>
3055 ········/// <param name="pc">the object to remove</param>
3056 ········/// <param name="checkAssoziations">true if child of a composition can't be deleted</param>
3057 ········private void Delete(IPersistenceCapable pc, bool checkAssoziations)
3058 ········{
3059 ············//Debug.WriteLine("Delete " + pc.NDOObjectId.Dump());
3060 ············//Debug.Indent();
3061 ············IDeleteNotifiable idn = pc as IDeleteNotifiable;
3062 ············if (idn != null)
3063 ················idn.OnDelete();
3064
3065 ············LoadAllRelations(pc);
3066 ············DeleteRelatedObjects(pc, checkAssoziations);
3067
3068 ············switch(pc.NDOObjectState)
3069 ············{
3070 ················case NDOObjectState.Transient:
3071 ····················throw new NDOException(80, "Cannot delete transient object: " + pc.NDOObjectId);
3072
3073 ················case NDOObjectState.Created:
3074 ····················DataRow row = cache.GetDataRow(pc);
3075 ····················row.Delete();
3076 ····················ArrayList cdosToDelete = new ArrayList();
3077 ····················foreach (IPersistenceCapable cdo in createdDirectObjects)
3078 ························if ((object)cdo == (object)pc)
3079 ····························cdosToDelete.Add(cdo);
3080 ····················foreach (object o in cdosToDelete)
3081 ························ObjectListManipulator.Remove(createdDirectObjects, o);
3082 ····················MakeObjectTransient(pc, true);
3083 ····················break;
3084 ················case NDOObjectState.Persistent:
3085 ····················if (!cache.IsLocked(pc)) // Deletes k�nnen durchaus mehrmals aufgerufen werden
3086 ························SaveObjectState(pc, true);
3087 ····················row = cache.GetDataRow(pc);
3088 ····················row.Delete();
3089 ····················pc.NDOObjectState = NDOObjectState.Deleted;
3090 ····················break;
3091 ················case NDOObjectState.Hollow:
3092 ····················if (!cache.IsLocked(pc)) // Deletes k�nnen durchaus mehrmals aufgerufen werden
3093 ························SaveFakeRow(pc);
3094 ····················row = cache.GetDataRow(pc);
3095 ····················row.Delete();
3096 ····················pc.NDOObjectState = NDOObjectState.Deleted;
3097 ····················break;
3098
3099 ················case NDOObjectState.PersistentDirty:
3100 ····················row = cache.GetDataRow(pc);
3101 ····················row.Delete();
3102 ····················pc.NDOObjectState··= NDOObjectState.Deleted;
3103 ····················break;
3104
3105 ················case NDOObjectState.Deleted:
3106 ····················break;
3107 ············}
3108
3109 ············//Debug.Unindent();
3110 ········}
3111
3112
3113 ········private void DeleteMappingTableEntry(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3114 ········{
3115 ············MappingTableEntry mte = null;
3116 ············foreach(MappingTableEntry e in createdMappingTableObjects)
3117 ············{
3118 ················if(e.ParentObject.NDOObjectId == pc.NDOObjectId && e.RelatedObject.NDOObjectId == child.NDOObjectId && e.Relation == r)
3119 ················{
3120 ····················mte = e;
3121 ····················break;
3122 ················}
3123 ············}
3124
3125 ············if(pc.NDOObjectState == NDOObjectState.Created || child.NDOObjectState == NDOObjectState.Created)
3126 ············{
3127 ················if (mte != null)
3128 ····················createdMappingTableObjects.Remove(mte);
3129 ············}
3130 ············else
3131 ············{
3132 ················if (mte == null)
3133 ····················createdMappingTableObjects.Add(new MappingTableEntry(pc, child, r, true));
3134 ············}
3135 ········}
3136
3137 ········private void DeleteOrNullForeignRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3138 ········{
3139 ············// Two tasks: a) Null the foreign key
3140 ············//··············b) remove the element from the foreign container
3141
3142 ············if (!r.Bidirectional)
3143 ················return;
3144
3145 ············// this keeps the oid valid
3146 ············if (GetClass(child.GetType()).Oid.IsDependent)
3147 ················return;
3148
3149 ············if(r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
3150 ············{
3151 ················LoadAndMarkDirty(child);
3152 ················mappings.SetRelationField(child, r.ForeignRelation.FieldName, null);
3153 ············}
3154 ············else //if(r.Multiplicity == RelationMultiplicity.List &&
3155 ················// r.ForeignRelation.Multiplicity == RelationMultiplicity.List)··
3156 ············{
3157 ················if (!child.NDOGetLoadState(r.ForeignRelation.Ordinal))
3158 ····················LoadRelation(child, r.ForeignRelation, true);
3159 ················IList l = mappings.GetRelationContainer(child, r.ForeignRelation);
3160 ················if (l == null)
3161 ····················throw new NDOException(67, "Can't remove object from the list " + child.GetType().FullName + "." + r.ForeignRelation.FieldName + ". The list is null.");
3162 ················ObjectListManipulator.Remove(l, pc);
3163 ················// Don't need to delete the mapping table entry, because that was done
3164 ················// through the parent.
3165 ············}
3166 ········}
3167
3168 ········private void DeleteOrNullRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3169 ········{
3170 ············// 1) Element····nomap····ass
3171 ············// 2) Element····nomap····comp
3172 ············// 3) Element····map········ass
3173 ············// 4) Element····map········comp
3174 ············// 5) List········nomap····ass
3175 ············// 6) List········nomap····comp
3176 ············// 7) List········map········ass
3177 ············// 8) List········map········comp
3178
3179 ············// Two tasks: Null foreign key and, if Composition, delete the child
3180
3181 ············// If Mapping Table, delete the entry - 3,7
3182 ············// If List and assoziation, null the foreign key in the foreign class - 5
3183 ············// If Element, null the foreign key in the own class 1,2,3,4
3184 ············// If composition, delete the child 2,4,6,8
3185
3186 ············// If the relObj is newly created
3187 ············ObjectListManipulator.Remove(createdDirectObjects, child);
3188 ············Class childClass = GetClass(child);
3189
3190 ············if (r.MappingTable != null)··// 3,7
3191 ············{················
3192 ················DeleteMappingTableEntry(pc, r, child);
3193 ············}
3194 ············else if (r.Multiplicity == RelationMultiplicity.List
3195 ················&& !r.Composition && !childClass.Oid.IsDependent) // 5
3196 ············{················
3197 ················LoadAndMarkDirty(child);
3198 ················DataRow row = this.cache.GetDataRow(child);
3199 ················foreach (ForeignKeyColumn fkColumnn in r.ForeignKeyColumns)
3200 ················{
3201 ····················row[fkColumnn.Name] = DBNull.Value;
3202 ····················child.NDOLoadState.ReplaceRowInfo(fkColumnn.Name, DBNull.Value);
3203 ················}
3204 ············}
3205 ············else if (r.Multiplicity == RelationMultiplicity.Element) // 1,2,3,4
3206 ············{
3207 ················LoadAndMarkDirty(pc);
3208 ············}
3209 ············if (r.Composition || childClass.Oid.IsDependent)
3210 ············{
3211 #if DEBUG
3212 ················if (child.NDOObjectState == NDOObjectState.Transient)
3213 ····················Debug.WriteLine("***** Object shouldn't be transient: " + child.GetType().FullName);
3214 #endif
3215 ················// Deletes the foreign key in case of List multiplicity
3216 ················// In case of Element multiplicity, the parent is either deleted,
3217 ················// or RemoveRelatedObject is called because the relation has been nulled.
3218 ················Delete(child);··
3219 ············}
3220 ········}
3221
3222 ········/// <summary>
3223 ········/// Remove a related object
3224 ········/// </summary>
3225 ········/// <param name="pc"></param>
3226 ········/// <param name="r"></param>
3227 ········/// <param name="child"></param>
3228 ········/// <param name="calledFromStateManager"></param>
3229 ········protected virtual void InternalRemoveRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable child, bool calledFromStateManager)
3230 ········{
3231 ············//TODO: We need a relation management, which is independent of
3232 ············//the state management of an object. At the moment the relation
3233 ············//lists or elements are cached for restore, if an object is marked dirty.
3234 ············//Thus we have to mark dirty our parent object in any case at the moment.
3235 ············if (calledFromStateManager)
3236 ················MarkDirty(pc);
3237
3238 ············// Object can be deleted in an OnDelete-Handler
3239 ············if (child.NDOObjectState == NDOObjectState.Deleted)
3240 ················return;
3241 ············//············Debug.WriteLine("InternalRemoveRelatedObject " + pc.GetType().Name + " " + r.FieldName + " " + child.GetType());
3242 ············// Preconditions
3243 ············// This is called either by DeleteRelatedObjects or by RemoveRelatedObject
3244 ············// The Object state is checked there
3245
3246 ············// If there is a composition in the opposite direction
3247 ············// && the other direction hasn't been processed
3248 ············// throw an exception.
3249 ············// If an exception is thrown at this point, have a look at IsLocked....
3250 ············if (r.Bidirectional && r.ForeignRelation.Composition
3251 ················&& !removeLock.IsLocked(child, r.ForeignRelation, pc))
3252 ················throw new NDOException(82, "Cannot remove related object " + child.GetType().FullName + " from parent " + pc.NDOObjectId.Dump() + ". Object must be removed through the parent.");
3253
3254 ············if (!removeLock.GetLock(pc, r, child))
3255 ················return;
3256
3257 ············try
3258 ············{
3259 ················// must be in this order, since the child
3260 ················// can be deleted in DeleteOrNullRelation
3261 ················//if (changeForeignRelations)
3262 ················DeleteOrNullForeignRelation(pc, r, child);
3263 ················DeleteOrNullRelation(pc, r, child);
3264 ············}
3265 ············finally
3266 ············{
3267 ················removeLock.Unlock(pc, r, child);
3268 ············}
3269
3270 ············this.relationChanges.Add( new RelationChangeRecord( pc, child, r.FieldName, false ) );
3271 ········}
3272
3273 ········private void DeleteRelatedObjects2(IPersistenceCapable pc, Class parentClass, bool checkAssoziations, Relation r)
3274 ········{
3275 ············//············Debug.WriteLine("DeleteRelatedObjects2 " + pc.GetType().Name + " " + r.FieldName);
3276 ············//············Debug.Indent();
3277 ············if (r.Multiplicity == RelationMultiplicity.Element)
3278 ············{
3279 ················IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
3280 ················if(child != null)
3281 ················{
3282 ····················//····················if(checkAssoziations && r.Bidirectional && !r.Composition)
3283 ····················//····················{
3284 ····················//························if (!r.ForeignRelation.Composition)
3285 ····················//························{
3286 ····················//····························mappings.SetRelationField(pc, r.FieldName, null);
3287 ····················//····························mappings.SetRelationField(child, r.ForeignRelation.FieldName, null);
3288 ····················//························}
3289 ····················//····························//System.Diagnostics.Debug.WriteLine("Nullen: pc = " + pc.GetType().Name + " child = " + child.GetType().Name);
3290 ····················//························else
3291 ····················//····························throw new NDOException(83, "Can't remove object of type " + pc.GetType().FullName + "; It is contained by an object of type " + child.GetType().FullName);
3292 ····················//····················}
3293 ····················InternalRemoveRelatedObject(pc, r, child, false);
3294 ················}
3295 ············}
3296 ············else
3297 ············{
3298 ················IList list = mappings.GetRelationContainer(pc, r);
3299 ················if(list != null && list.Count > 0)
3300 ················{
3301 ····················//····················if(checkAssoziations && r.Bidirectional && !r.Composition)
3302 ····················//····················{
3303 ····················//························throw new xxNDOException(84, "Cannot delete object " + pc.NDOObjectId + " in an assoziation. Remove related objects first.");
3304 ····················//····················}
3305 ····················// Since RemoveRelatedObjects probably changes the list,
3306 ····················// we iterate through a copy of the list.
3307 ····················ArrayList al = new ArrayList(list);
3308 ····················foreach(IPersistenceCapable relObj in al)
3309 ····················{
3310 ························InternalRemoveRelatedObject(pc, r, relObj, false);
3311 ····················}
3312 ················}
3313 ············}
3314 ············//············Debug.Unindent();
3315 ········}
3316
3317 ········/// <summary>
3318 ········/// Remove all related objects from a parent.
3319 ········/// </summary>
3320 ········/// <param name="pc">the parent object</param>
3321 ········/// <param name="checkAssoziations"></param>
3322 ········private void DeleteRelatedObjects(IPersistenceCapable pc, bool checkAssoziations)
3323 ········{
3324 ············//············Debug.WriteLine("DeleteRelatedObjects " + pc.NDOObjectId.Dump());
3325 ············//············Debug.Indent();
3326 ············// delete all related objects:
3327 ············Class parentClass = GetClass(pc);
3328 ············// Remove Assoziations first
3329 ············foreach(Relation r in parentClass.Relations)
3330 ············{
3331 ················if (!r.Composition)
3332 ····················DeleteRelatedObjects2(pc, parentClass, checkAssoziations, r);
3333 ············}
3334 ············foreach(Relation r in parentClass.Relations)
3335 ············{
3336 ················if (r.Composition)
3337 ····················DeleteRelatedObjects2(pc, parentClass, checkAssoziations, r);
3338 ············}
3339
3340 ············//············Debug.Unindent();
3341 ········}
3342
3343 ········/// <summary>
3344 ········/// Delete a list of objects
3345 ········/// </summary>
3346 ········/// <param name="list">the list of objects to remove</param>
3347 ········public void Delete(IList list)
3348 ········{
3349 ············for (int i = 0; i < list.Count; i++)
3350 ············{
3351 ················IPersistenceCapable pc = (IPersistenceCapable) list[i];
3352 ················Delete(pc);
3353 ············}
3354 ········}
3355
3356 ········/// <summary>
3357 ········/// Make object hollow. All relations will be unloaded and object data will be
3358 ········/// newly fetched during the next touch of a persistent field.
3359 ········/// </summary>
3360 ········/// <param name="o"></param>
3361 ········public virtual void MakeHollow(object o)
3362 ········{
3363 ············IPersistenceCapable pc = CheckPc(o);
3364 ············MakeHollow(pc, false);
3365 ········}
3366
3367 ········/// <summary>
3368 ········/// Make the object hollow if it is persistent. Unload all complex data.
3369 ········/// </summary>
3370 ········/// <param name="o"></param>
3371 ········/// <param name="recursive">if true then unload related objects as well</param>
3372 ········public virtual void MakeHollow(object o, bool recursive)
3373 ········{
3374 ············IPersistenceCapable pc = CheckPc(o);
3375 ············if(pc.NDOObjectState == NDOObjectState.Hollow)
3376 ················return;
3377 ············if(pc.NDOObjectState != NDOObjectState.Persistent)
3378 ············{
3379 ················throw new NDOException(85, "MakeHollow: Illegal state for this operation (" + pc.NDOObjectState.ToString() + ")");
3380 ············}
3381 ············pc.NDOObjectState = NDOObjectState.Hollow;
3382 ············MakeRelationsHollow(pc, recursive);
3383 ········}
3384
3385 ········/// <summary>
3386 ········/// Make all objects of a list hollow.
3387 ········/// </summary>
3388 ········/// <param name="list">the list of objects that should be made hollow</param>
3389 ········public virtual void MakeHollow(System.Collections.IList list)
3390 ········{
3391 ············MakeHollow(list, false);
3392 ········}
3393
3394 ········/// <summary>
3395 ········/// Make all objects of a list hollow.
3396 ········/// </summary>
3397 ········/// <param name="list">the list of objects that should be made hollow</param>
3398 ········/// <param name="recursive">if true then unload related objects as well</param>
3399 ········public void MakeHollow(System.Collections.IList list, bool recursive)
3400 ········{
3401 ············foreach (IPersistenceCapable pc in list)
3402 ················MakeHollow(pc, recursive);················
3403 ········}
3404
3405 ········/// <summary>
3406 ········/// Make all unlocked objects in the cache hollow.
3407 ········/// </summary>
3408 ········public virtual void MakeAllHollow()
3409 ········{
3410 ············foreach(var pc in cache.UnlockedObjects)
3411 ············{
3412 ················MakeHollow(pc, false);
3413 ············}
3414 ········}
3415
3416 ········/// <summary>
3417 ········/// Make relations hollow.
3418 ········/// </summary>
3419 ········/// <param name="pc">The parent object</param>
3420 ········/// <param name="recursive">If true, the function unloads related objects as well.</param>
3421 ········private void MakeRelationsHollow(IPersistenceCapable pc, bool recursive)
3422 ········{
3423 ············Class c = GetClass(pc);
3424 ············foreach(Relation r in c.Relations)
3425 ············{
3426 ················if (r.Multiplicity == RelationMultiplicity.Element)
3427 ················{
3428 ····················mappings.SetRelationField(pc, r.FieldName, null);
3429 ····················//····················IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
3430 ····················//····················if((null != child) && recursive)
3431 ····················//····················{
3432 ····················//························MakeHollow(child, true);
3433 ····················//····················}
3434 ················}
3435 ················else
3436 ················{
3437 ····················if (!pc.NDOGetLoadState(r.Ordinal))
3438 ························continue;
3439 ····················// Help GC by clearing lists
3440 ····················IList l = mappings.GetRelationContainer(pc, r);
3441 ····················if(l != null)
3442 ····················{
3443 ························if(recursive)
3444 ························{
3445 ····························MakeHollow(l, true);
3446 ························}
3447 ························l.Clear();
3448 ····················}
3449 ····················// Hollow relation
3450 ····················mappings.SetRelationContainer(pc, r, null);
3451 ················}
3452 ············}
3453 ············ClearRelationState(pc);
3454 ········}
3455
3456 ········private void ClearRelationState(IPersistenceCapable pc)
3457 ········{
3458 ············Class cl = GetClass(pc);
3459 ············foreach(Relation r in cl.Relations)
3460 ················pc.NDOSetLoadState(r.Ordinal, false);
3461 ········}
3462
3463 ········private void SetRelationState(IPersistenceCapable pc)
3464 ········{
3465 ············Class cl = GetClass(pc);
3466 ············// Due to a bug in the enhancer the constructors are not always patched right,
3467 ············// so NDOLoadState might be uninitialized
3468 ············if (pc.NDOLoadState == null)
3469 ············{
3470 ················FieldInfo fi = new BaseClassReflector(pc.GetType()).GetField("_ndoLoadState", BindingFlags.Instance | BindingFlags.NonPublic);
3471 ················if (fi == null)
3472 ····················throw new InternalException(3131, "pm.SetRelationState: No FieldInfo for _ndoLoadState");
3473 ················fi.SetValue(pc, new LoadState());
3474 ············}
3475
3476 ············// After serialization the relation load state is null
3477 ············if (pc.NDOLoadState.RelationLoadState == null)
3478 ················pc.NDOLoadState.RelationLoadState = new BitArray(LoadState.RelationLoadStateSize);
3479 ············foreach(Relation r in cl.Relations)
3480 ················pc.NDOSetLoadState(r.Ordinal, true);
3481 ········}
3482
3483 ········/// <summary>
3484 ········/// Creates an object of a given type and resolves constructor parameters using the container.
3485 ········/// </summary>
3486 ········/// <param name="t">The type of the persistent object</param>
3487 ········/// <returns></returns>
3488 ········public IPersistenceCapable CreateObject(Type t)
3489 ········{
3490 ············return (IPersistenceCapable) ActivatorUtilities.CreateInstance( ServiceProvider, t );
3491 ········}
3492
3493 ········/// <summary>
3494 ········/// Creates an object of a given type and resolves constructor parameters using the container.
3495 ········/// </summary>
3496 ········/// <typeparam name="T">The type of the object to create.</typeparam>
3497 ········/// <returns></returns>
3498 ········public T CreateObject<T>()
3499 ········{
3500 ············return (T)CreateObject( typeof( T ) );
3501 ········}
3502
3503 ········/// <summary>
3504 ········/// Finds an object in the object cache and loads the object from the database
3505 ········/// in case of a cache miss.
3506 ········/// </summary>
3507 ········/// <param name="shortId"></param>
3508 ········/// <returns>A persistent object</returns>
3509 ········public async Task <IPersistenceCapable> GetObjectByShortIdAsync(string shortId)
3510 ········{
3511 ············var pc = FindObject(shortId);
3512 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
3513 ················await LoadDataAsync( pc ).ConfigureAwait(false);
3514 ············return pc;
3515 ········}
3516
3517 ········/// <summary>
3518 ········/// Gets the requested object. It first builds an ObjectId using the type and the
3519 ········/// key data. Then it uses FindObject to retrieve the object. No database access
3520 ········/// is performed.
3521 ········/// </summary>
3522 ········/// <param name="t">The type of the object to retrieve.</param>
3523 ········/// <param name="keyData">The key value to build the object id.</param>
3524 ········/// <returns>A hollow object</returns>
3525 ········/// <remarks>If the key value is of a wrong type, an exception will be thrown, if the object state changes from hollow to persistent.</remarks>
3526 ········public IPersistenceCapable FindObject(Type t, object keyData)
3527 ········{
3528 ············ObjectId oid = ObjectIdFactory.NewObjectId(t, GetClass(t), keyData, this.typeManager);
3529 ············return FindObject(oid);
3530 ········}
3531
3532 ········/// <summary>
3533 ········/// Finds an object using a short id.
3534 ········/// </summary>
3535 ········/// <param name="encodedShortId"></param>
3536 ········/// <returns></returns>
3537 ········public IPersistenceCapable FindObject(string encodedShortId)
3538 ········{
3539 ············string shortId = encodedShortId.Decode();
3540 ············string[] arr = shortId.Split( '-' );
3541 ············if (arr.Length != 3)
3542 ················throw new ArgumentException( "The format of the string is not valid", "shortId" );
3543 ············Type t = shortId.GetObjectType(this);··// try readable format
3544 ············if (t == null)
3545 ············{
3546 ················int typeCode = 0;
3547 ················if (!int.TryParse( arr[2], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out typeCode ))
3548 ····················throw new ArgumentException( "The string doesn't represent a loadable type", "shortId" );
3549 ················t = this.typeManager[typeCode];
3550 ················if (t == null)
3551 ····················throw new ArgumentException( "The string doesn't represent a loadable type", "shortId" );
3552 ············}
3553
3554 ············Class cls = GetClass( t );
3555 ············if (cls == null)
3556 ················throw new ArgumentException( "The type identified by the string is not persistent or is not managed by the given mapping file", "shortId" );
3557
3558 ············object[] keydata = new object[cls.Oid.OidColumns.Count];
3559 ············string[] oidValues = arr[2].Split( ' ' );
3560
3561 ············int i = 0;
3562 ············foreach (var oidValue in oidValues)
3563 ············{
3564 ················Type oidType = cls.Oid.OidColumns[i].SystemType;
3565 ················if (oidType == typeof( int ))
3566 ················{
3567 ····················int key;
3568 ····················if (!int.TryParse( oidValue, out key ))
3569 ························throw new ArgumentException( $"The ShortId value at index {i} doesn't contain an int value", nameof(encodedShortId) );
3570 ····················if (key > (int.MaxValue >> 1))
3571 ························key = -(int.MaxValue - key);
3572 ····················keydata[i] = key;
3573 ················}
3574 ················else if (oidType == typeof( Guid ))
3575 ················{
3576 ····················Guid key;
3577 ····················if (!Guid.TryParse( oidValue, out key ))
3578 ························throw new ArgumentException( $"The ShortId value at index {i} doesn't contain an Guid value", nameof( encodedShortId ) );
3579 ····················keydata[i] = key;
3580 ················}
3581 ················else if (oidType == typeof( string ))
3582 ················{
3583 ····················keydata[i] = oidValue;
3584 ················}
3585 ················else
3586 ················{
3587 ····················throw new ArgumentException( $"The oid type at index {i} of the persistent type {t} can't be used by a ShortId: {oidType.FullName}", nameof( encodedShortId ) );
3588 ················}
3589
3590 ················i++;
3591 ············}
3592
3593 ············if (keydata.Length == 1)
3594 ················return FindObject( t, keydata[0] );
3595
3596 ············return FindObject( t, keydata );············
3597 ········}
3598
3599 ········/// <summary>
3600 ········/// Gets the requested object. If it is in the cache, the cached object is returned, otherwise, a new (hollow)
3601 ········/// instance of the object is returned. In either case, the DB is not accessed!
3602 ········/// </summary>
3603 ········/// <param name="id">Object id</param>
3604 ········/// <returns>The object to retrieve in hollow state</returns>········
3605 ········public IPersistenceCapable FindObject(ObjectId id)
3606 ········{
3607 ············if(id == null)
3608 ············{
3609 ················throw new ArgumentNullException("id");
3610 ············}
3611
3612 ············if(!id.IsValid())
3613 ············{
3614 ················throw new NDOException(86, "FindObject: Invalid object id. Object does not exist");
3615 ············}
3616
3617 ············IPersistenceCapable pc = cache.GetObject(id);
3618 ············if(pc == null)
3619 ············{
3620 ················pc = CreateObject(id.Id.Type);
3621 ················pc.NDOObjectId = id;
3622 ················pc.NDOStateManager = sm;
3623 ················pc.NDOObjectState = NDOObjectState.Hollow;
3624 ················cache.UpdateCache(pc);
3625 ············}
3626 ············return pc;
3627 ········}
3628
3629
3630 ········/// <summary>
3631 ········/// Reload an object from the database.
3632 ········/// </summary>
3633 ········/// <param name="o">The object to be reloaded.</param>
3634 ········public void Refresh(object o)
3635 ········{
3636 ············RefreshAsync( o ).ConfigureAwait( false ).GetAwaiter().GetResult();
3637 ········}
3638
3639 ········/// <summary>
3640 ········/// Reload an object from the database asynchronously.
3641 ········/// </summary>
3642 ········/// <param name="o">The object to be reloaded.</param>
3643 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3644 ········public virtual async Task RefreshAsync( object o, CancellationToken cancellationToken = default )
3645 ········{
3646 ············using (EnterOperation())
3647 ············{
3648 ················await RefreshInternalAsync( o, cancellationToken ).ConfigureAwait( false );
3649 ············}
3650 ········}
3651
3652 ········async Task RefreshInternalAsync( object o, CancellationToken cancellationToken )
3653 ········{
3654 ············IPersistenceCapable pc = CheckPc(o);
3655 ············if(pc.NDOObjectState == NDOObjectState.Transient || pc.NDOObjectState == NDOObjectState.Deleted)
3656 ············{
3657 ················throw new NDOException(87, "Refresh: Illegal state " + pc.NDOObjectState + " for this operation");
3658 ············}
3659
3660 ············if(pc.NDOObjectState == NDOObjectState.Created || pc.NDOObjectState == NDOObjectState.PersistentDirty)
3661 ················return; // Cannot update objects in current transaction
3662
3663 ············MakeHollow(pc);
3664 ············await LoadDataAsync( pc, cancellationToken ).ConfigureAwait( false );
3665 ········}
3666
3667 ········/// <summary>
3668 ········/// Refresh a list of objects.
3669 ········/// </summary>
3670 ········/// <param name="list">The list of objects to be refreshed.</param>
3671 ········public void Refresh(IList list)
3672 ········{
3673 ············RefreshAsync( list ).ConfigureAwait( false ).GetAwaiter().GetResult();
3674 ········}
3675
3676 ········/// <summary>
3677 ········/// Refresh a list of objects asynchronously.
3678 ········/// </summary>
3679 ········/// <param name="list">The list of objects to be refreshed.</param>
3680 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3681 ········/// <remarks>The objects are refreshed sequentially.</remarks>
3682 ········public virtual async Task RefreshAsync( IList list, CancellationToken cancellationToken = default )
3683 ········{
3684 ············using (EnterOperation())
3685 ············{
3686 ················foreach (IPersistenceCapable pc in list)
3687 ····················await RefreshAsync( (object) pc, cancellationToken ).ConfigureAwait( false );
3688 ············}
3689 ········}
3690
3691 ········/// <summary>
3692 ········/// Refreshes all unlocked objects in the cache.
3693 ········/// </summary>
3694 ········public void RefreshAll()
3695 ········{
3696 ············RefreshAllAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
3697 ········}
3698
3699 ········/// <summary>
3700 ········/// Refreshes all unlocked objects in the cache asynchronously.
3701 ········/// </summary>
3702 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3703 ········public virtual Task RefreshAllAsync( CancellationToken cancellationToken = default )
3704 ········{
3705 ············return RefreshAsync( cache.UnlockedObjects.ToList(), cancellationToken );
3706 ········}
3707
3708 ········/// <summary>
3709 ········/// Closes the PersistenceManager and releases all resources.
3710 ········/// </summary>
3711 ········public override async Task CloseAsync()
3712 ········{
3713 ············if (this.isClosing)
3714 ················return;
3715 ············this.isClosing = true;
3716 ············await TransactionScope.DisposeAsync().ConfigureAwait( false );
3717 ············UnloadCache();
3718 ············await base.CloseAsync().ConfigureAwait( false );
3719 ········}
3720
3721 ········internal void LogIfVerbose( string msg )
3722 ········{
3723 ············if (Logger != null && Logger.IsEnabled( LogLevel.Debug ))
3724 ················Logger.LogDebug( msg );
3725 ········}
3726
3727
3728 ········#endregion
3729
3730
3731
3732 #region Query engine
3733
3734
3735 ········/// <summary>
3736 ········/// Returns a virtual table for Linq queries.
3737 ········/// </summary>
3738 ········/// <typeparam name="T"></typeparam>
3739 ········/// <returns></returns>
3740 ········public VirtualTable<T> Objects<T>() //where T: IPersistenceCapable
3741 ········{
3742 ············return new VirtualTable<T>( this );
3743 ········}
3744
3745 ········
3746 ········/// <summary>
3747 ········/// Suppose, you had a directed 1:n relation from class A to class B. If you load an object of type B,
3748 ········/// a foreign key pointing to a row in the table A is read as part of the B row. But since B doesn't have
3749 ········/// a relation to A the foreign key would get lost if we discard the row after building the B object. To
3750 ········/// not lose the foreign key it will be stored as part of the object.
3751 ········/// </summary>
3752 ········/// <param name="cl"></param>
3753 ········/// <param name="pc"></param>
3754 ········/// <param name="row"></param>
3755 ········void ReadLostForeignKeysFromRow(Class cl, IPersistenceCapable pc, DataRow row)
3756 ········{
3757 ············if (cl.FKColumnNames != null && pc.NDOLoadState != null)
3758 ············{
3759 ················//················Debug.WriteLine("GetLostForeignKeysFromRow " + pc.NDOObjectId.Dump());
3760 ················KeyValueList kvl = new KeyValueList(cl.FKColumnNames.Count());
3761 ················foreach(string colName in cl.FKColumnNames)
3762 ····················kvl.Add(new KeyValuePair(colName, row[colName]));
3763 ················pc.NDOLoadState.LostRowInfo = kvl;················
3764 ············}
3765 ········}
3766
3767 ········/// <summary>
3768 ········/// Writes information into the data row, which cannot be stored in the object.
3769 ········/// </summary>
3770 ········/// <param name="cl"></param>
3771 ········/// <param name="pc"></param>
3772 ········/// <param name="row"></param>
3773 ········protected virtual void WriteLostForeignKeysToRow(Class cl, IPersistenceCapable pc, DataRow row)
3774 ········{
3775 ············if (cl.FKColumnNames != null)
3776 ············{
3777 ················//················Debug.WriteLine("WriteLostForeignKeys " + pc.NDOObjectId.Dump());
3778 ················KeyValueList kvl = (KeyValueList)pc.NDOLoadState.LostRowInfo;
3779 ················if (kvl == null)
3780 ····················throw new NDOException(88, "Can't find foreign keys for the relations of the object " + pc.NDOObjectId.Dump());
3781 ················foreach (KeyValuePair pair in kvl)
3782 ····················row[(string) pair.Key] = pair.Value;
3783 ············}
3784 ········}
3785
3786 ········void Row2Object(Class cl, IPersistenceCapable pc, DataRow row)
3787 ········{
3788 ············ReadObject(pc, row, cl.ColumnNames, 0);
3789 ············ReadTimeStamp(cl, pc, row);
3790 ············ReadLostForeignKeysFromRow(cl, pc, row);
3791 ············LoadRelated1To1Objects(pc, row);
3792 ············pc.NDOObjectState = NDOObjectState.Persistent;
3793 ········}
3794
3795
3796 ········/// <summary>
3797 ········/// Convert a data table to objects. Note that the table might only hold objects of the specified type.
3798 ········/// </summary>
3799 ········internal IList DataTableToIList(Type t, ICollection rows, bool hollow)
3800 ········{
3801 ············IList queryResult = GenericListReflector.CreateList(t, rows.Count);
3802 ············if (rows.Count == 0)
3803 ················return queryResult;
3804
3805 ············IList callbackObjects = new ArrayList();
3806 ············Class cl = GetClass(t);
3807 ············if (t.IsGenericTypeDefinition)
3808 ············{
3809 ················if (cl.TypeNameColumn == null)
3810 ····················throw new NDOException(104, "No type name column defined for generic type '" + t.FullName + "'. Check your mapping file.");
3811 ················IEnumerator en = rows.GetEnumerator();
3812 ················en.MoveNext();··// Move to the first element
3813 ················DataRow testrow = (DataRow)en.Current;
3814 ················if (testrow.Table.Columns[cl.TypeNameColumn.Name] == null)
3815 ····················throw new InternalException(3333, "DataTableToIList: TypeNameColumn isn't defined in the schema.");
3816 ············}
3817
3818 ············foreach(DataRow row in rows)
3819 ············{
3820 ················Type concreteType = t;
3821 ················if (t.IsGenericTypeDefinition)··// type information is in the row
3822 ················{
3823 ····················if (row[cl.TypeNameColumn.Name] == DBNull.Value)
3824 ····················{
3825 ························ObjectId tempid = ObjectIdFactory.NewObjectId(t, cl, row, this.typeManager);
3826 ························throw new NDOException(105, "Null entry in the TypeNameColumn of the type '" + t.FullName + "'. Oid = " + tempid.ToString());
3827 ····················}
3828 ····················string typeStr = (string)row[cl.TypeNameColumn.Name];
3829 ····················concreteType = Type.GetType(typeStr);
3830 ····················if (concreteType == null)
3831 ························throw new NDOException(106, "Can't load generic type " + typeStr);
3832 ················}
3833 ················ObjectId id = ObjectIdFactory.NewObjectId(concreteType, cl, row, this.typeManager);
3834 ················IPersistenceCapable pc = cache.GetObject(id);················
3835 ················if(pc == null)
3836 ················{
3837 ····················pc = CreateObject( concreteType );
3838 ····················pc.NDOObjectId = id;
3839 ····················pc.NDOStateManager = sm;
3840 ····················// If the object shouldn't be hollow, this will be overwritten later.
3841 ····················pc.NDOObjectState = NDOObjectState.Hollow;
3842 ················}
3843 ················// If we have found a non hollow object, the time stamp remains the old one.
3844 ················// In every other case we use the new time stamp.
3845 ················// Note, that there could be a hollow object in the cache.
3846 ················// We need the time stamp in hollow objects in order to correctly
3847 ················// delete objects using fake rows.
3848 ················if (pc.NDOObjectState == NDOObjectState.Hollow)
3849 ················{
3850 ····················ReadTimeStamp(cl, pc, row);
3851 ················}
3852 ················if(!hollow && pc.NDOObjectState != NDOObjectState.PersistentDirty)
3853 ················{
3854 ····················Row2Object(cl, pc, row);
3855 ····················if ((pc as IPersistenceNotifiable) != null)
3856 ························callbackObjects.Add(pc);
3857 ················}
3858
3859 ················cache.UpdateCache(pc);
3860 ················queryResult.Add(pc);
3861 ············}
3862 ············// Make shure this is the last statement before returning
3863 ············// to the caller, so the user can recursively use persistent
3864 ············// objects
3865 ············foreach(IPersistenceNotifiable ipn in callbackObjects)
3866 ················ipn.OnLoaded();
3867
3868 ············return queryResult;
3869 ········}
3870
3871 #endregion
3872
3873 #region Cache Management
3874 ········/// <summary>
3875 ········/// Remove all unused entries from the cache.
3876 ········/// </summary>
3877 ········public void CleanupCache()
3878 ········{
3879 ············GC.Collect(GC.MaxGeneration);
3880 ············GC.WaitForPendingFinalizers();
3881 ············cache.Cleanup();
3882 ········}
3883
3884 ········/// <summary>
3885 ········/// Remove all unlocked objects from the cache. Use with care!
3886 ········/// </summary>
3887 ········public void UnloadCache()
3888 ········{
3889 ············cache.Unload();
3890 ········}
3891 #endregion
3892
3893 ········/// <summary>
3894 ········/// Default encryption key for NDO
3895 ········/// </summary>
3896 ········/// <remarks>
3897 ········/// We recommend strongly to use an own encryption key, which can be set with this property.
3898 ········/// </remarks>
3899 ········public virtual byte[] EncryptionKey
3900 ········{
3901 ············get
3902 ············{
3903 ················if (this.encryptionKey == null)
3904 ····················this.encryptionKey = new byte[] { 0x09,0xA2,0x79,0x5C,0x99,0xFF,0xCB,0x8B,0xA3,0x37,0x76,0xC8,0xA6,0x5D,0x6D,0x66,
3905 ······················································0xE2,0x74,0xCF,0xF0,0xF7,0xEA,0xC4,0x82,0x1E,0xD5,0x19,0x4C,0x5A,0xB4,0x89,0x4D };
3906 ················return this.encryptionKey;
3907 ············}
3908 ············set { this.encryptionKey = value; }
3909 ········}
3910
3911 ········/// <summary>
3912 ········/// Hollow mode: If true all objects are made hollow after each transaction.
3913 ········/// </summary>
3914 ········public virtual bool HollowMode
3915 ········{
3916 ············get { return hollowMode; }
3917 ············set { hollowMode = value; }
3918 ········}
3919
3920 ········internal TypeManager TypeManager
3921 ········{
3922 ············get { return typeManager; }
3923 ········}
3924
3925 ········/// <summary>
3926 ········/// Sets or gets transaction mode. Uses TransactionMode enum.
3927 ········/// </summary>
3928 ········/// <remarks>
3929 ········/// Set this value before you start any transactions.
3930 ········/// </remarks>
3931 ········public TransactionMode TransactionMode
3932 ········{
3933 ············get { return TransactionScope.TransactionMode; }
3934 ············set { TransactionScope.TransactionMode = value; }
3935 ········}
3936
3937 ········/// <summary>
3938 ········/// Sets or gets the Isolation Level.
3939 ········/// </summary>
3940 ········/// <remarks>
3941 ········/// Set this value before you start any transactions.
3942 ········/// </remarks>
3943 ········public IsolationLevel IsolationLevel
3944 ········{
3945 ············get { return TransactionScope.IsolationLevel; }
3946 ············set { TransactionScope.IsolationLevel = value; }
3947 ········}
3948
3949 ········internal class MappingTableEntry
3950 ········{
3951 ············private IPersistenceCapable parentObject;
3952 ············private IPersistenceCapable relatedObject;
3953 ············private Relation relation;
3954 ············private bool deleteEntry;
3955 ············
3956 ············public MappingTableEntry(IPersistenceCapable pc, IPersistenceCapable relObj, Relation r) : this(pc, relObj, r, false)
3957 ············{
3958 ············}
3959 ············
3960 ············public MappingTableEntry(IPersistenceCapable pc, IPersistenceCapable relObj, Relation r, bool deleteEntry)
3961 ············{
3962 ················parentObject = pc;
3963 ················relatedObject = relObj;
3964 ················relation = r;
3965 ················this.deleteEntry = deleteEntry;
3966 ············}
3967
3968 ············public bool DeleteEntry
3969 ············{
3970 ················get
3971 ················{
3972 ····················return deleteEntry;
3973 ················}
3974 ············}
3975
3976 ············public IPersistenceCapable ParentObject
3977 ············{
3978 ················get
3979 ················{
3980 ····················return parentObject;
3981 ················}
3982 ············}
3983
3984 ············public IPersistenceCapable RelatedObject
3985 ············{
3986 ················get
3987 ················{
3988 ····················return relatedObject;
3989 ················}
3990 ············}
3991
3992 ············public Relation Relation
3993 ············{
3994 ················get
3995 ················{
3996 ····················return relation;
3997 ················}
3998 ············}
3999 ········}
4000
4001 ········/// <summary>
4002 ········/// Get a DataRow representing the given object.
4003 ········/// </summary>
4004 ········/// <param name="o"></param>
4005 ········/// <returns></returns>
4006 ········public DataRow GetClonedDataRow( object o )
4007 ········{
4008 ············IPersistenceCapable pc = CheckPc( o );
4009
4010 ············if (pc.NDOObjectState == NDOObjectState.Deleted || pc.NDOObjectState == NDOObjectState.Transient)
4011 ················throw new Exception( "GetDataRow: State of the object must not be Deleted or Transient." );
4012
4013 ············DataRow row = cache.GetDataRow( pc );
4014 ············DataTable newTable = row.Table.Clone();
4015 ············newTable.ImportRow( row );
4016 ············row = newTable.Rows[0];
4017
4018 ············Class cls = mappings.FindClass(o.GetType());
4019 ············WriteObject( pc, row, cls.ColumnNames );
4020 ············WriteForeignKeysToRow( pc, row );
4021
4022 ············return row;
4023 ········}
4024
4025 ········/// <summary>
4026 ········/// Gets an object, which shows all changes applied to the given object.
4027 ········/// This function can be used to build an audit system.
4028 ········/// </summary>
4029 ········/// <param name="o"></param>
4030 ········/// <returns>An ExpandoObject</returns>
4031 ········public ChangeLog GetChangeSet( object o )
4032 ········{
4033 ············var changeLog = new ChangeLog(this);
4034 ············changeLog.Initialize( o );
4035 ············return changeLog;
4036 ········}
4037
4038 ········/// <summary>
4039 ········/// Outputs a revision number representing the assembly version.
4040 ········/// </summary>
4041 ········/// <remarks>This can be used for debugging purposes</remarks>
4042 ········public int Revision
4043 ········{
4044 ············get
4045 ············{
4046 ················Version v = new AssemblyName( GetType().Assembly.FullName ).Version;
4047 ················string vstring = String.Format( "{0}{1:D2}{2}{3:D2}", v.Major, v.Minor, v.Build, v.MinorRevision );
4048 ················return int.Parse( vstring );
4049 ············}
4050 ········}
4051 ····}
4052 }
4053