Datei: NDODLL/PersistenceManager.cs

Last Commit (f676ed7)
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(), ex);
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 ················if (r.MappingTable != null)
698 ····················CheckDuplicateMappingTableEntry(pc, r, relObj);
699
700 ················//TODO: We need a relation management, which is independent of
701 ················//the state management of an object. Currently the relation
702 ················//lists or elements are cached for restore, if an object is marked dirty.
703 ················//Thus we have to mark dirty our parent object in any case at the moment.
704 ················MarkDirty(pc);
705
706 ················//We should mark pc as dirty if we have a 1:1 w/o mapping table
707 ················//We should mark relObj as dirty if we have a 1:n w/o mapping table
708 ················//The latter happens in CreateAddedObjectRow
709
710 ················Class relClass = GetClass(relObj);
711
712 ················if (r.Multiplicity == RelationMultiplicity.Element
713 ····················&& r.HasSubclasses
714 ····················&& r.MappingTable == null················
715 ····················&& !this.HasOwnerCreatedIds
716 ····················&& GetClass(pc).Oid.HasAutoincrementedColumn
717 ····················&& !relClass.HasGuidOid)
718 ················{
719 ····················if (pc.NDOObjectState == NDOObjectState.Created && (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient ))
720 ························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.");
721 ····················if (r.Composition)
722 ························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.");
723 ····················if (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient)
724 ························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." );
725 ················}
726
727 ················bool isDependent = relClass.Oid.IsDependent;
728
729 ················if (r.Multiplicity == RelationMultiplicity.Element && isDependent)
730 ····················throw new NDOException(28, "Relations to intermediate classes must have RelationMultiplicity.List.");
731
732 ················// Need to patch pc into the relation relObj->pc, because
733 ················// the oid is built on base of this information
734 ················if (isDependent)
735 ················{
736 ····················CheckDependentKeyPreconditions(pc, r, relObj, relClass);
737 ················}
738
739 ················if (r.Composition || isDependent)
740 ················{
741 ····················if (!isMerging || relObj.NDOObjectState == NDOObjectState.Transient)
742 ························MakePersistent(relObj);
743 ················}
744
745 ················if(r.MappingTable == null)
746 ················{
747 ····················if (r.Bidirectional)
748 ····················{
749 ························// This object hasn't been saved yet, so the key is wrong.
750 ························// Therefore, the child must be written twice to update the foreign key.
751 #if trace
752 ························System.Text.StringBuilder sb = new System.Text.StringBuilder();
753 ························if (r.Multiplicity == RelationMultiplicity.Element)
754 ····························sb.Append("1");
755 ························else
756 ····························sb.Append("n");
757 ························sb.Append(":");
758 ························if (r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
759 ····························sb.Append("1");
760 ························else
761 ····························sb.Append("n");
762 ························sb.Append ("OwnCreatedOther");
763 ························sb.Append(relObj.NDOObjectState.ToString());
764 ························sb.Append(' ');
765
766 ························sb.Append(types[0].ToString());
767 ························sb.Append(' ');
768 ························sb.Append(types[1].ToString());
769 ························Debug.WriteLine(sb.ToString());
770 #endif
771 ························//························if (r.Multiplicity == RelationMultiplicity.Element
772 ························//····························&& r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
773 ························//························{
774 ························// Element means:
775 ························// pc is keyholder
776 ························// -> relObj is saved first
777 ························// -> UpdateOrder(pc) > UpdateOrder(relObj)
778 ························// Both are Created - use type sort order
779 ························if (pc.NDOObjectState == NDOObjectState.Created && (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient)
780 ····························&& GetClass(pc).Oid.HasAutoincrementedColumn && GetClass(relObj).Oid.HasAutoincrementedColumn)
781 ························{
782 ····························if (mappings.GetUpdateOrder(pc.GetType())
783 ································< mappings.GetUpdateOrder(relObj.GetType()))
784 ································createdDirectObjects.Add(pc);
785 ····························else
786 ································createdDirectObjects.Add( relObj );
787 ························}
788 ····················}
789 ····················if (r.Multiplicity == RelationMultiplicity.List)
790 ····················{
791 ························CreateAddedObjectRow(pc, r, relObj, r.Composition);
792 ····················}
793 ················}
794 ················else
795 ················{
796 ····················// Adding an object, which was removed in the same transaction, cancels the deletion.
797 ····················MappingTableEntry deleteEntry = FindMappingTableEntry(pc, r, relObj);
798 ····················if (deleteEntry != null)
799 ························createdMappingTableObjects.Remove(deleteEntry);
800 ····················else
801 ························createdMappingTableObjects.Add(new MappingTableEntry(pc, relObj, r));
802 ················}
803 ················if(r.Bidirectional)
804 ················{
805 ····················if (r.Multiplicity == RelationMultiplicity.List && mappings.GetRelationField(relObj, r.ForeignRelation.FieldName) == null)
806 ····················{
807 ························if ( r.ForeignRelation.Multiplicity == RelationMultiplicity.Element )
808 ····························mappings.SetRelationField(relObj, r.ForeignRelation.FieldName, pc);
809 ····················}
810 ····················else if ( !addLock.IsLocked( pc ) )
811 ····················{
812 ························PatchForeignRelation( pc, r, relObj );
813 ····················}
814 ················}
815
816 ················this.relationChanges.Add( new RelationChangeRecord( pc, relObj, r.FieldName, true ) );
817 ············}
818 ············finally
819 ············{
820 ················addLock.Unlock(relObj);
821 ················//Debug.Unindent();
822 ············}
823 ········}
824
825 ········/// <summary>
826 ········/// Returns an integer value which determines the rank of the given type in the update order list.
827 ········/// </summary>
828 ········/// <param name="t">The type to determine the update order.</param>
829 ········/// <returns>An integer value determining the rank of the given type in the update order list.</returns>
830 ········/// <remarks>
831 ········/// This method is used by NDO for diagnostic purposes. There is no value in using this method in user code.
832 ········/// </remarks>
833 ········public int GetUpdateRank(Type t)
834 ········{
835 ············return mappings.GetUpdateOrder(t);
836 ········}
837
838 ········/// <summary>
839 ········/// Add a related object to the specified object.
840 ········/// </summary>
841 ········/// <param name="pc">the parent object</param>
842 ········/// <param name="r">the relation mapping info</param>
843 ········/// <param name="relObj">the related object that should be added</param>
844 ········protected virtual void AddRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
845 ········{
846 ············//············string idstr;
847 ············//············if (relObj.NDOObjectId == null)
848 ············//················idstr = relObj.GetType().ToString();
849 ············//············else
850 ············//················idstr = relObj.NDOObjectId.Dump();
851 ············//Debug.WriteLine("AddRelatedObject " + pc.NDOObjectId.Dump() + " " + idstr);
852 ············//Debug.Indent();
853
854 ············Class relClass = GetClass(relObj);
855 ············bool isDependent = relClass.Oid.IsDependent;
856
857 ············// Do some checks to guarantee that the assignment is correct
858 ············if(r.Composition)
859 ············{
860 ················if(relObj.NDOObjectState != NDOObjectState.Transient)
861 ················{
862 ····················throw new NDOException(58, "Can only add transient objects in Composite relation " + pc.GetType().FullName + "->" + r.ReferencedTypeName + ".");
863 ················}
864 ············}
865 ············else
866 ············{
867 ················if(relObj.NDOObjectState == NDOObjectState.Transient && !isDependent)
868 ················{
869 ····················throw new NDOException(59, "Can only add persistent objects in Assoziation " + pc.GetType().FullName + "->" + r.ReferencedTypeName + ".");
870 ················}
871 ············}
872
873 ············if(!r.ReferencedType.IsAssignableFrom(relObj.GetType()))
874 ············{
875 ················throw new NDOException(60, "AddRelatedObject: Related object must be assignable to type: " + r.ReferencedTypeName + ". Assigned object was: " + relObj.NDOObjectId.Dump() + " Type = " + relObj.GetType());
876 ············}
877
878 ············InternalAddRelatedObject(pc, r, relObj, false);
879
880 ········}
881
882 ········private void CheckDependentKeyPreconditions(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj, Class relClass)
883 ········{
884 ············// Need to patch pc into the relation relObj->pc, because
885 ············// the oid is built on base of this information
886 ············// The second relation has to be set before adding relObj
887 ············// to the relation list.
888 ············PatchForeignRelation(pc, r, relObj);
889 ············IPersistenceCapable parent;
890 ············foreach (Relation oidRelation in relClass.Oid.Relations)
891 ············{
892 ················parent = (IPersistenceCapable)mappings.GetRelationField(relObj, oidRelation.FieldName);
893 ················if (parent == null)
894 ····················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.");
895 ················if (parent.NDOObjectState == NDOObjectState.Transient)
896 ····················throw new NDOException(59, "Can only add persistent objects in Assoziation " + relClass.FullName + "." + oidRelation.FieldName + ". Make the object of type " + parent.GetType().FullName + " persistent.");
897
898 ············}
899 ········}
900
901
902 ········/// <summary>
903 ········/// Remove a related object from the specified object.
904 ········/// </summary>
905 ········/// <param name="pc">the parent object</param>
906 ········/// <param name="fieldName">Field name of the relation</param>
907 ········/// <param name="relObj">the related object that should be removed</param>
908 ········internal virtual void RemoveRelatedObject(IPersistenceCapable pc, string fieldName, IPersistenceCapable relObj)
909 ········{
910 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient);
911 ············Relation r = mappings.FindRelation(pc, fieldName);
912 ············InternalRemoveRelatedObject(pc, r, relObj, true);
913 ········}
914
915 ········/// <summary>
916 ········/// Registers a listener which will be notified, if a new connection is opened.
917 ········/// </summary>
918 ········/// <param name="listener">Delegate of a listener function</param>
919 ········/// <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>
920 ········public virtual void RegisterConnectionListener(OpenConnectionListener listener)
921 ········{
922 ············this.openConnectionListener = listener;
923 ········}
924
925 ········internal string OnNewConnection(NDO.Mapping.Connection conn)
926 ········{
927 ············if (openConnectionListener != null)
928 ················return openConnectionListener(conn);
929 ············return conn.Name;
930 ········}
931
932
933 ········/*
934 ········doCommit should be:
935 ········
936 ····················Query····Save····Save(true)
937 ········Optimistic····1········1········0
938 ········Pessimistic····0········1········0
939 ············
940 ········Deferred Mode············
941 ····················Query····Save····Save(true)
942 ········Optimistic····0········1········0
943 ········Pessimistic····0········1········0
944 ········ */
945
946 ········internal void CheckEndTransaction(bool doCommit)
947 ········{
948 ············CheckEndTransactionAsync( doCommit ).ConfigureAwait( false ).GetAwaiter().GetResult();
949 ········}
950
951 ········internal async Task CheckEndTransactionAsync( bool doCommit, CancellationToken cancellationToken = default )
952 ········{
953 ············if (doCommit)
954 ············{
955 ················await TransactionScope.CompleteAsync( cancellationToken ).ConfigureAwait( false );
956 ············}
957 ········}
958
959 ········internal Task CheckTransactionAsync( IPersistenceHandlerBase handler, Type t, CancellationToken cancellationToken = default )
960 ········{
961 ············return CheckTransactionAsync( handler, this.GetClass( t ).Connection, cancellationToken );
962 ········}
963
964 ········int activeOperation;
965 ········readonly AsyncLocal<bool> ownsOperation = new AsyncLocal<bool>();
966
967 ········/// <summary>
968 ········/// Marks the begin of an operation with database access. Detects concurrent usage of the PersistenceManager.
969 ········/// </summary>
970 ········/// <param name="caller">The name of the calling method</param>
971 ········/// <returns>An object, which marks the end of the operation if disposed.</returns>
972 ········/// <remarks>
973 ········/// Nested calls in the same logical flow (e.g. lazy loading in an OnSaving handler) are allowed.
974 ········/// The AsyncLocal flows with the ExecutionContext into all awaited calls, but not back to the caller of an async method.
975 ········/// So two concurrently started tasks don't share the ownership.
976 ········/// </remarks>
977 ········internal OperationGuard EnterOperation( [CallerMemberName] string caller = null )
978 ········{
979 ············if (this.ownsOperation.Value)
980 ················return default;··// Nested call in the same logical flow
981 ············if (Interlocked.CompareExchange( ref this.activeOperation, 1, 0 ) != 0)
982 ················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." );
983 ············this.ownsOperation.Value = true;
984 ············return new OperationGuard( this );
985 ········}
986
987 ········internal readonly struct OperationGuard : IDisposable
988 ········{
989 ············readonly PersistenceManager pm;
990
991 ············public OperationGuard( PersistenceManager pm )
992 ············{
993 ················this.pm = pm;
994 ············}
995
996 ············public void Dispose()
997 ············{
998 ················if (this.pm == null)
999 ····················return;··// Nested call: nothing to release
1000 ················this.pm.ownsOperation.Value = false;
1001 ················Volatile.Write( ref this.pm.activeOperation, 0 );
1002 ············}
1003 ········}
1004
1005 ········/// <summary>
1006 ········/// Each and every database operation has to be preceded by a call to this function.
1007 ········/// </summary>
1008 ········internal async Task CheckTransactionAsync( IPersistenceHandlerBase handler, Connection ndoConn, CancellationToken cancellationToken = default )
1009 ········{
1010 ············await TransactionScope.CheckTransactionAsync( cancellationToken ).ConfigureAwait( false );
1011 ············
1012 ············if (handler.Connection == null)
1013 ············{
1014 ················handler.Connection = await TransactionScope.GetConnectionAsync(ndoConn, () =>
1015 ················{
1016 ····················IProvider p = ndoConn.Parent.GetProvider( ndoConn );
1017 ····················string connStr = this.OnNewConnection( ndoConn );
1018 ····················var connection = p.NewConnection( connStr );
1019 ····················if (connection == null)
1020 ························throw new NDOException( 119, $"Can't construct connection for {connStr}. The provider returns null." );
1021 ····················LogIfVerbose( $"Creating a connection object for {ndoConn.DisplayName}" );
1022 ····················return connection;
1023 ················}, cancellationToken ).ConfigureAwait( false );
1024 ············}
1025
1026 ············if (TransactionMode != TransactionMode.None)
1027 ············{
1028 ················handler.Transaction = TransactionScope.GetTransaction( ndoConn.ID );
1029 ············}
1030
1031 ············// There are tests with a handler mock that always returns zero for the Connection property.
1032 ············if (handler.Connection != null && handler.Connection.State != ConnectionState.Open)
1033 ············{
1034 ················await handler.Connection.OpenAsync( cancellationToken ).ConfigureAwait( false );
1035 ················var serverId = ndoConn.Provider.GetConnectionId( handler.Connection );
1036 ················LogIfVerbose( $"Opening connection {serverId} = '{ndoConn.DisplayName}'" );
1037 ············}
1038 ········}
1039
1040 ········/// <summary>
1041 ········/// Event Handler for the ConcurrencyError event of the IPersistenceHandler.
1042 ········/// We try to tell the object which caused the concurrency exception, that a collicion occured.
1043 ········/// This is possible if there is a listener for the CollisionEvent.
1044 ········/// Else we throw an exception.
1045 ········/// </summary>
1046 ········/// <param name="ex">Concurrency Exception which was catched during update.</param>
1047 ········private void OnConcurrencyError(System.Data.DBConcurrencyException ex)
1048 ········{
1049 ············DataRow row = ex.Row;
1050 ············if (row == null || CollisionEvent == null || CollisionEvent.GetInvocationList().Length == 0)
1051 ················throw(ex);
1052 ············if (row.RowState == DataRowState.Detached)
1053 ················return;
1054 ············foreach (Cache.Entry e in cache.LockedObjects)
1055 ············{
1056 ················if (e.row == row)
1057 ················{
1058 ····················CollisionEvent(e.pc);
1059 ····················return;
1060 ················}
1061 ············}
1062 ············throw ex;
1063 ········}
1064
1065
1066 ········private void ReadObject(IPersistenceCapable pc, DataRow row, string[] fieldNames, int startIndex)
1067 ········{
1068 ············Class cl = GetClass(pc);
1069 ············string[] etypes = cl.EmbeddedTypes.ToArray();
1070 ············Dictionary<string,MemberInfo> persistentFields = null;
1071 ············if (etypes.Length > 0)
1072 ············{
1073 ················FieldMap fm = new FieldMap(cl);
1074 ················persistentFields = fm.PersistentFields;
1075 ············}
1076 ············foreach(string s in etypes)
1077 ············{
1078 ················try
1079 ················{
1080 ····················NDO.Mapping.Field f = cl.FindField(s);
1081 ····················if (f == null)
1082 ························continue;
1083 ····················object o = row[f.Column.Name];
1084 ····················string[] arr = s.Split('.');
1085 ····················// Suche Embedded Type-Feld mit Namen arr[0]
1086 ····················BaseClassReflector bcr = new BaseClassReflector(pc.GetType());
1087 ····················FieldInfo parentFi = bcr.GetField(arr[0], BindingFlags.NonPublic | BindingFlags.Instance);
1088 ····················// Hole das Embedded Object
1089 ····················object parentOb = parentFi.GetValue(pc);
1090
1091 ····················if (parentOb == null)
1092 ························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]));
1093
1094 ····················// Suche darin das Feld mit Namen Arr[1]
1095
1096 ····················FieldInfo childFi = parentFi.FieldType.GetField(arr[1], BindingFlags.NonPublic | BindingFlags.Instance);
1097 ····················Type childType = childFi.FieldType;
1098
1099 ····················// Don't initialize value types, if DBNull is stored in the field.
1100 ····················// Exception: DateTime and Guid.
1101 ····················if (o == DBNull.Value && childType.IsValueType
1102 ························&& childType != typeof(Guid)
1103 ························&& childType != typeof(DateTime))
1104 ························continue;
1105
1106 ····················if (childType == typeof(DateTime))
1107 ····················{
1108 ························if (o == DBNull.Value)
1109 ····························o = DateTime.MinValue;
1110 ····················}
1111 ····················if (childType.IsClass)
1112 ····················{
1113 ························if (o == DBNull.Value)
1114 ····························o = null;
1115 ····················}
1116
1117 ····················if (childType == typeof (Guid))
1118 ····················{
1119 ························if (o == DBNull.Value)
1120 ····························o = Guid.Empty;
1121 ························if (o is string)
1122 ························{
1123 ····························childFi.SetValue(parentOb, new Guid((string)o));
1124 ························}
1125 ························else if (o is Guid)
1126 ························{
1127 ····························childFi.SetValue(parentOb, o);
1128 ························}
1129 ························else if (o is byte[])
1130 ························{
1131 ····························childFi.SetValue(parentOb, new Guid((byte[])o));
1132 ························}
1133 ························else
1134 ····························throw new Exception(string.Format("Can't convert Guid field to column type {0}.", o.GetType().FullName));
1135 ····················}
1136 ····················else if (childType.IsSubclassOf(typeof(System.Enum)))
1137 ····················{
1138 ························object childOb = childFi.GetValue(parentOb);
1139 ························FieldInfo valueFi = childType.GetField("value__");
1140 ························valueFi.SetValue(childOb, o);
1141 ························childFi.SetValue(parentOb, childOb);
1142 ····················}
1143 ····················else
1144 ····················{
1145 ························childFi.SetValue(parentOb, o);
1146 ····················}
1147 ················}
1148 ················catch (Exception ex)
1149 ················{
1150 ····················string msg = "Error while writing the embedded object {0} of an object of type {1}. Check your mapping file.\n{2}";
1151
1152 ····················throw new NDOException(68, string.Format(msg, s, pc.GetType().FullName, ex.Message), ex);
1153 ················}
1154
1155 ············}
1156 ············
1157 ············try
1158 ············{
1159 ················if (cl.HasEncryptedFields)
1160 ················{
1161 ····················foreach (var field in cl.Fields.Where( f => f.Encrypted ))
1162 ····················{
1163 ························string name = field.Column.Name;
1164 ························string s = (string) row[name];
1165 ························string es = AesHelper.Decrypt( s, EncryptionKey );
1166 ························row[name] = es;
1167 ····················}
1168 ················}
1169 ················pc.NDORead(row, fieldNames, startIndex);
1170 ············}
1171 ············catch (Exception ex)
1172 ············{
1173 ················throw new NDOException(69, "Error while writing to a field of an object of type " + pc.GetType().FullName + ". Check your mapping file.\n"
1174 ····················+ ex.Message, ex);
1175 ············}
1176 ········}
1177
1178 ········/// <summary>
1179 ········/// Executes a sql script to generate the database tables.
1180 ········/// The function will execute any sql statements in the script
1181 ········/// which are valid according to the
1182 ········/// rules of the underlying database. Result sets are ignored.
1183 ········/// </summary>
1184 ········/// <param name="scriptFile">The script file to execute.</param>
1185 ········/// <param name="conn">A connection object, containing the connection
1186 ········/// string to the database, which should be altered.</param>
1187 ········/// <returns>A string array with error messages or the string "OK" for each of the statements in the file.</returns>
1188 ········/// <remarks>
1189 ········/// If the Connection object is invalid or null, a NDOException with ErrorNumber 44 will be thrown.
1190 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1191 ········/// Their message property will appear in the result array.
1192 ········/// If the script doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1193 ········/// </remarks>
1194 ········public string[] BuildDatabase( string scriptFile, Connection conn )
1195 ········{
1196 ············return BuildDatabase( scriptFile, conn, Encoding.UTF8 );
1197 ········}
1198
1199 ········/// <summary>
1200 ········/// Executes a sql script to generate the database tables.
1201 ········/// The function will execute any sql statements in the script
1202 ········/// which are valid according to the
1203 ········/// rules of the underlying database. Result sets are ignored.
1204 ········/// </summary>
1205 ········/// <param name="scriptFile">The script file to execute.</param>
1206 ········/// <param name="conn">A connection object, containing the connection
1207 ········/// string to the database, which should be altered.</param>
1208 ········/// <param name="encoding">The encoding of the script file. Default is UTF8.</param>
1209 ········/// <returns>A string array with error messages or the string "OK" for each of the statements in the file.</returns>
1210 ········/// <remarks>
1211 ········/// If the Connection object is invalid or null, a NDOException with ErrorNumber 44 will be thrown.
1212 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1213 ········/// Their message property will appear in the result array.
1214 ········/// If the script doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1215 ········/// </remarks>
1216 ········public string[] BuildDatabase(string scriptFile, Connection conn, Encoding encoding)
1217 ········{
1218 ············StreamReader sr = new StreamReader(scriptFile, encoding);
1219 ············string s = sr.ReadToEnd();
1220 ············sr.Close();
1221 ············string[] arr = s.Split(';');
1222 ············string last = arr[arr.Length - 1];
1223 ············bool lastInvalid = (last == null || last.Trim() == string.Empty);
1224 ············string[] result = new string[arr.Length - (lastInvalid ? 1 : 0)];
1225 ············using (var handler = GetSqlPassThroughHandler())
1226 ············{
1227 ················int i = 0;
1228 ················string ok = "OK";
1229 ················foreach (string statement in arr)
1230 ················{
1231 ····················if (statement != null && statement.Trim() != string.Empty)
1232 ····················{
1233 ························try
1234 ························{
1235 ····························handler.Execute(statement);
1236 ····························result[i] = ok;
1237 ························}
1238 ························catch (Exception ex)
1239 ························{
1240 ····························result[i] = ex.Message;
1241 ························}
1242 ····················}
1243 ····················i++;
1244 ················}
1245 ················CheckEndTransaction(true);
1246 ············}
1247 ············return result;
1248 ········}
1249
1250 ········/// <summary>
1251 ········/// Executes a sql script to generate the database tables.
1252 ········/// The function will execute any sql statements in the script
1253 ········/// which are valid according to the
1254 ········/// rules of the underlying database. Result sets are ignored.
1255 ········/// </summary>
1256 ········/// <param name="scriptFile">The script file to execute.</param>
1257 ········/// <returns></returns>
1258 ········/// <remarks>
1259 ········/// This function takes the first Connection object in the Connections list
1260 ········/// of the Mapping file und executes the script using that connection.
1261 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1262 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1263 ········/// Their message property will appear in the result array.
1264 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1265 ········/// </remarks>
1266 ········public string[] BuildDatabase(string scriptFile)
1267 ········{
1268 ············if (!File.Exists(scriptFile))
1269 ················throw new NDOException(48, "Script file " + scriptFile + " doesn't exist.");
1270 ············if (!this.mappings.Connections.Any())
1271 ················throw new NDOException(48, "Mapping file doesn't define a connection.");
1272 ············Connection conn = new Connection( this.mappings );
1273 ············Connection originalConnection = (Connection)this.mappings.Connections.First();
1274 ············conn.Name = OnNewConnection( originalConnection );
1275 ············conn.Type = originalConnection.Type;
1276 ············//Connection conn = (Connection) this.mappings.Connections[0];
1277 ············return BuildDatabase(scriptFile, conn);
1278 ········}
1279
1280 ········/// <summary>
1281 ········/// Executes a sql script to generate the database tables.
1282 ········/// The function will execute any sql statements in the script
1283 ········/// which are valid according to the
1284 ········/// rules of the underlying database. Result sets are ignored.
1285 ········/// </summary>
1286 ········/// <returns>
1287 ········/// A string array, containing the error messages produced by the statements
1288 ········/// contained in the script.
1289 ········/// </returns>
1290 ········/// <remarks>
1291 ········/// The sql script is assumed to be the executable name of the entry assembly with the
1292 ········/// extension .ndo.sql. Use BuildDatabase(string) to provide a path to a script.
1293 ········/// If the executable name can't be determined a NDOException with ErrorNumber 49 will be thrown.
1294 ········/// This function takes the first Connection object in the Connections list
1295 ········/// of the Mapping file und executes the script using that connection.
1296 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1297 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1298 ········/// Their message property will appear in the result array.
1299 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1300 ········/// </remarks>
1301 ········public string[] BuildDatabase()
1302 ········{
1303 ············Assembly ass = Assembly.GetEntryAssembly();
1304 ············if (ass == null)
1305 ················throw new NDOException(49, "Can't determine the path of the entry assembly - please pass a sql script path as argument to BuildDatabase.");
1306 ············string file = Path.ChangeExtension(ass.Location, ".ndo.sql");
1307 ············return BuildDatabase(file);
1308 ········}
1309
1310 ········/// <summary>
1311 ········/// Gets a SqlPassThroughHandler object which can be used to execute raw Sql statements.
1312 ········/// </summary>
1313 ········/// <param name="conn">Optional: The NDO-Connection to the database to be used.</param>
1314 ········/// <returns>An ISqlPassThroughHandler implementation</returns>
1315 ········public ISqlPassThroughHandler GetSqlPassThroughHandler( Connection conn = null )
1316 ········{
1317 ············if (!this.mappings.Connections.Any())
1318 ················throw new NDOException( 48, "Mapping file doesn't define a connection." );
1319 ············if (conn == null)
1320 ············{
1321 ················conn = new Connection( this.mappings );
1322 ················Connection originalConnection = (Connection) this.mappings.Connections.First();
1323 ················conn.Name = OnNewConnection( originalConnection );
1324 ················conn.Type = originalConnection.Type;
1325 ············}
1326
1327 ············return new SqlPassThroughHandler( this, conn );
1328 ········}
1329
1330 ········/// <summary>
1331 ········/// Gets a SqlPassThroughHandler object which can be used to execute raw Sql statements.
1332 ········/// </summary>
1333 ········/// <param name="predicate">A predicate defining which connection has to be used.</param>
1334 ········/// <returns>An ISqlPassThroughHandler implementation</returns>
1335 ········public ISqlPassThroughHandler GetSqlPassThroughHandler( Func<Connection, bool> predicate )
1336 ········{
1337 ············if (!this.mappings.Connections.Any())
1338 ················throw new NDOException( 48, "The Mapping file doesn't define a connection." );
1339 ············Connection conn = this.mappings.Connections.FirstOrDefault( predicate );
1340 ············if (conn == null)
1341 ················throw new NDOException( 48, "The Mapping file doesn't define a connection with this predicate." );
1342 ············return GetSqlPassThroughHandler( conn );
1343 ········}
1344
1345 ········/// <summary>
1346 ········/// Executes a xml script to generate the database tables.
1347 ········/// The function will generate and execute sql statements to perform
1348 ········/// the changes described by the xml.
1349 ········/// </summary>
1350 ········/// <returns></returns>
1351 ········/// <remarks>
1352 ········/// The script file is the first file found with the search string [AssemblyNameWithoutExtension].ndodiff.[SchemaVersion].xml.
1353 ········/// If several files match the search string biggest file name in the default sort order will be executed.
1354 ········/// This function takes the first Connection object in the Connections list
1355 ········/// of the Mapping file und executes the script using that connection.
1356 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1357 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1358 ········/// Their message property will appear in the result string array.
1359 ········/// If no script file exists, a NDOException with ErrorNumber 48 will be thrown.
1360 ········/// Note that an additional command is executed, which will update the NDOSchemaVersion entry.
1361 ········/// </remarks>
1362 ········public string[] PerformSchemaTransitions()
1363 ········{
1364 ············Assembly ass = Assembly.GetEntryAssembly();
1365 ············if (ass == null)
1366 ················throw new NDOException(49, "Can't determine the path of the entry assembly - please pass a sql script path as argument to PerformSchemaTransitions.");
1367 ············string mask = Path.GetFileNameWithoutExtension( ass.Location ) + ".ndodiff.*.xml";
1368 ············List<string> fileNames = Directory.GetFiles( Path.GetDirectoryName( ass.Location ), mask ).ToList();
1369 ············if (fileNames.Count == 0)
1370 ················return new String[] { String.Format( "No xml script file with a name like {0} found.", mask ) };
1371 ············if (fileNames.Count > 1)
1372 ················fileNames.Sort( ( fn1, fn2 ) => CompareFileName( fn1, fn2 ) );
1373 ············return PerformSchemaTransitions( fileNames[0] );
1374 ········}
1375
1376
1377 ········/// <summary>
1378 ········/// Executes a xml script to generate the database tables.
1379 ········/// The function will generate and execute sql statements to perform
1380 ········/// the changes described by the xml.
1381 ········/// </summary>
1382 ········/// <param name="scriptFile">The script file to execute.</param>
1383 ········/// <returns></returns>
1384 ········/// <remarks>
1385 ········/// This function takes the first Connection object in the Connections list
1386 ········/// of the Mapping file und executes the script using that connection.
1387 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1388 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1389 ········/// Their message property will appear in the result string array.
1390 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1391 ········/// Note that an additional command is executed, which will update the NDOSchemaVersion entry.
1392 ········/// </remarks>
1393 ········public string[] PerformSchemaTransitions(string scriptFile)
1394 ········{
1395 ············if (!File.Exists(scriptFile))
1396 ················throw new NDOException(48, "Script file " + scriptFile + " doesn't exist.");
1397
1398 ············if (!this.mappings.Connections.Any())
1399 ················throw new NDOException(48, "Mapping file doesn't define any connection.");
1400 ············Connection conn = new Connection( mappings );
1401 ············Connection originalConnection = mappings.Connections.First();
1402 ············conn.Name = OnNewConnection( originalConnection );
1403 ············conn.Type = originalConnection.Type;
1404 ············return PerformSchemaTransitions(scriptFile, conn);
1405 ········}
1406
1407
1408 ········int CompareFileName( string fn1, string fn2)
1409 ········{
1410 ············Regex regex = new Regex( @"ndodiff\.(.+)\.xml" );
1411 ············Match match = regex.Match( fn1 );
1412 ············string v1 = match.Groups[1].Value;
1413 ············match = regex.Match( fn2 );
1414 ············string v2 = match.Groups[1].Value;
1415 ············return new Version( v2 ).CompareTo( new Version( v1 ) );
1416 ········}
1417
1418 ········Guid[] GetSchemaIds(Connection ndoConn, string schemaName, IProvider provider)
1419 ········{
1420 ············var connection = provider.NewConnection( ndoConn.Name );
1421 ············var resultList = new List<Guid>();
1422
1423 ············using (var handler = GetSqlPassThroughHandler())
1424 ············{
1425 ················string[] TableNames = provider.GetTableNames( connection );
1426 ················if (TableNames.Any( t => String.Compare( t, "NDOSchemaIds", true ) == 0 ))
1427 ················{
1428 ····················var schemaIds = provider.GetQualifiedTableName("NDOSchemaIds");
1429 ····················var sn = provider.GetQuotedName("SchemaName");
1430 ····················var id = provider.GetQuotedName("Id");
1431 ····················string sql = $"SELECT {id} from {schemaIds} WHERE {sn} ";
1432 ····················if (String.IsNullOrEmpty(schemaName))
1433 ························sql += "IS NULL;";
1434 ····················else
1435 ························sql += $"LIKE '{schemaName}'";
1436
1437 ····················using(IDataReader dr = handler.Execute(sql, true))
1438 ····················{
1439 ························while (dr.Read())
1440 ····························resultList.Add( dr.GetGuid( 0 ) );
1441 ····················}
1442 ················}
1443 ················else
1444 ················{
1445 ····················SchemaTransitionGenerator schemaTransitionGenerator = new SchemaTransitionGenerator( ProviderFactory, ndoConn.Type, this.mappings );
1446 ····················var gt = typeof(Guid);
1447 ····················var gtype = $"{gt.FullName},{ new AssemblyName( gt.Assembly.FullName ).Name }";
1448 ····················var st = typeof(String);
1449 ····················var stype = $"{st.FullName},{ new AssemblyName( st.Assembly.FullName ).Name }";
1450 ····················var dt = typeof(DateTime);
1451 ····················var dtype = $"{st.FullName},{ new AssemblyName( st.Assembly.FullName ).Name }";
1452 ····················string transition = $@"<NdoSchemaTransition>
1453 ····<CreateTable name=""NDOSchemaIds"">
1454 ······<CreateColumn name=""SchemaName"" type=""{stype}"" allowNull=""True"" />
1455 ······<CreateColumn name=""Id"" type=""{gtype}"" size=""36"" isPrimary=""True"" />
1456 ······<CreateColumn name=""InsertTime"" type=""{dtype}"" size=""36"" />
1457 ····</CreateTable>
1458 </NdoSchemaTransition>";
1459 ····················XElement transitionElement = XElement.Parse(transition);
1460
1461 ····················string sql = schemaTransitionGenerator.Generate( transitionElement );
1462 ····················handler.Execute(sql);
1463 ················}
1464 ················handler.CommitTransaction();
1465 ············}
1466
1467 ············return resultList.ToArray();
1468 ········}
1469
1470 ········/// <summary>
1471 ········/// Executes a xml script to generate the database tables.
1472 ········/// The function will generate and execute sql statements to perform
1473 ········/// the changes described by the xml.
1474 ········/// </summary>
1475 ········/// <param name="scriptFile">The xml script file.</param>
1476 ········/// <param name="ndoConn">The connection to be used to perform the schema changes.</param>
1477 ········/// <returns>A list of strings about the states of the different schema change commands.</returns>
1478 ········/// <remarks>Note that an additional command is executed, which will update the NDOSchemaVersion entry.</remarks>
1479 ········public string[] PerformSchemaTransitions(string scriptFile, Connection ndoConn)
1480 ········{
1481 ············string schemaName = null;
1482 ············// Gespeicherte Version ermitteln.
1483 ············XElement transitionElements = XElement.Load( scriptFile );
1484 ············if (transitionElements.Attribute( "schemaName" ) != null)
1485 ················schemaName = transitionElements.Attribute( "schemaName" ).Value;
1486
1487 ············IProvider provider = this.mappings.GetProvider( ndoConn );
1488 ············var installedIds = GetSchemaIds( ndoConn, schemaName, provider );
1489 ············var newIds = new List<Guid>();
1490 ············SchemaTransitionGenerator schemaTransitionGenerator = new SchemaTransitionGenerator( ProviderFactory, ndoConn.Type, this.mappings );
1491
1492 ············// dtLiteral contains the leading and trailing quotes
1493 ············var dtLiteral = provider.GetSqlLiteral( DateTime.Now );
1494 ············var ndoSchemaIds = provider.GetQualifiedTableName("NDOSchemaIds");
1495 ············var schName = provider.GetQuotedName("SchemaName");
1496 ············var idCol = provider.GetQuotedName("Id");
1497 ············var insertTime = provider.GetQuotedName("InsertTime");
1498 ············var results = new List<string>();
1499
1500 ············// Each transitionElement gets it's own transaction.
1501 ············// The insert into NDOSchemaIds is part of the transaction.
1502 ············// If an error occurs, InternalPerformSchemaTransitions aborts the transaction.
1503 ············foreach (XElement transitionElement in transitionElements.Elements( "NdoSchemaTransition" ))
1504 ············{
1505 ················var id = transitionElement.Attribute("id")?.Value;
1506 ················if (id == null)
1507 ····················continue;
1508 ················var gid = new Guid(id);
1509 ················if (installedIds.Contains( gid ))
1510 ····················continue;
1511
1512 ················var sb = new StringBuilder();
1513 ················sb.Append( schemaTransitionGenerator.Generate( transitionElement ) );
1514 ················newIds.Add( gid );
1515
1516 ················if (schemaName != null)
1517 ····················sb.Append( $"INSERT INTO {ndoSchemaIds} ({schName},{idCol},{insertTime}) VALUES ('{schemaName}','{gid}',{dtLiteral});" );
1518 ················else
1519 ····················sb.Append( $"INSERT INTO {ndoSchemaIds} ({schName},{idCol},{insertTime}) VALUES (NULL,'{gid}',{dtLiteral});" );
1520
1521 ················results.AddRange( InternalPerformSchemaTransitions( ndoConn, sb.ToString() ) );
1522 ············}
1523
1524 ············return results.ToArray();
1525 ········}
1526
1527 ········private string[] InternalPerformSchemaTransitions( Connection ndoConn, string sql )
1528 ········{
1529 ············string[] arr = sql.Split( ';' );
1530
1531 ············string last = arr[arr.Length - 1];
1532 ············bool lastInvalid = (last == null || last.Trim() == string.Empty);
1533 ············string[] result = new string[arr.Length - (lastInvalid ? 1 : 0)];
1534 ············int i = 0;
1535 ············string ok = "OK";
1536 ············using (var handler = GetSqlPassThroughHandler())
1537 ············{
1538 ················handler.BeginTransaction();
1539 ················var doCommit = true;
1540 ················foreach (string statement in arr)
1541 ················{
1542 ····················if (!String.IsNullOrWhiteSpace(statement))
1543 ····················{
1544 ························try
1545 ························{
1546 ····························handler.Execute( statement.Trim() );
1547 ····························result[i] = ok;
1548 ························}
1549 ························catch (Exception ex)
1550 ························{
1551 ····························result[i] = ex.Message;
1552 ····························doCommit = false;
1553 ························}
1554 ····················}
1555 ····················i++;
1556 ················}
1557 ················if (doCommit)
1558 ····················handler.CommitTransaction();
1559 ················else
1560 ····················AbortTransaction();
1561 ············}
1562
1563 ············return result;
1564 ········}
1565 ········
1566 ········/// <summary>
1567 ········/// Transfers Data from the object to the DataRow
1568 ········/// </summary>
1569 ········/// <param name="pc"></param>
1570 ········/// <param name="row"></param>
1571 ········/// <param name="fieldNames"></param>
1572 ········/// <param name="startIndex"></param>
1573 ········protected virtual void WriteObject(IPersistenceCapable pc, DataRow row, string[] fieldNames, int startIndex)
1574 ········{
1575 ············Class cl = GetClass( pc );
1576 ············try
1577 ············{
1578 ················pc.NDOWrite(row, fieldNames, startIndex);
1579 ················if (cl.HasEncryptedFields)
1580 ················{
1581 ····················foreach (var field in cl.Fields.Where( f => f.Encrypted ))
1582 ····················{
1583 ························string name = field.Column.Name;
1584 ························string s = (string) row[name];
1585 ························string es = AesHelper.Encrypt( s, EncryptionKey );
1586 ························row[name] = es;
1587 ····················}
1588 ················}
1589 ············}
1590 ············catch (Exception ex)
1591 ············{
1592 ················throw new NDOException(70, "Error while reading a field of an object of type " + pc.GetType().FullName + ". Check your mapping file.\n"
1593 ····················+ ex.Message, ex);
1594 ············}
1595
1596 ············if (cl.TypeNameColumn != null)
1597 ············{
1598 ················Type t = pc.GetType();
1599 ················row[cl.TypeNameColumn.Name] = t.FullName + "," + t.Assembly.GetName().Name;
1600 ············}
1601
1602 ············var etypes = cl.EmbeddedTypes;
1603 ············foreach(string s in etypes)
1604 ············{
1605 ················try
1606 ················{
1607 ····················NDO.Mapping.Field f = cl.FindField(s);
1608 ····················if (f == null)
1609 ························continue;
1610 ····················string[] arr = s.Split('.');
1611 ····················// Suche Feld mit Namen arr[0] als object
1612 ····················BaseClassReflector bcr = new BaseClassReflector(pc.GetType());
1613 ····················FieldInfo parentFi = bcr.GetField(arr[0], BindingFlags.NonPublic | BindingFlags.Instance);
1614 ····················Object parentOb = parentFi.GetValue(pc);
1615 ····················if (parentOb == null)
1616 ························throw new Exception(String.Format("The field {0} is null. Initialize the field in your default constructor.", arr[0]));
1617 ····················// Suche darin das Feld mit Namen Arr[1]
1618 ····················FieldInfo childFi = parentFi.FieldType.GetField(arr[1], BindingFlags.NonPublic | BindingFlags.Instance);
1619 ····················object o = childFi.GetValue(parentOb);
1620 ····················if (o == null
1621 ························|| o is DateTime && (DateTime) o == DateTime.MinValue
1622 ························|| o is Guid && (Guid) o == Guid.Empty)
1623 ························o = DBNull.Value;
1624 ····················row[f.Column.Name] = o;
1625 ················}
1626 ················catch (Exception ex)
1627 ················{
1628 ····················string msg = "Error while reading the embedded object {0} of an object of type {1}. Check your mapping file.\n{2}";
1629
1630 ····················throw new NDOException(71, string.Format(msg, s, pc.GetType().FullName, ex.Message), ex);
1631 ················}
1632 ············}
1633 ········}
1634
1635 ········/// <summary>
1636 ········/// Check, if the specific field is loaded. If not, LoadData will be called.
1637 ········/// </summary>
1638 ········/// <param name="o">The parent object.</param>
1639 ········/// <param name="fieldOrdinal">A number to identify the field.</param>
1640 ········public virtual void LoadField(object o, int fieldOrdinal)
1641 ········{
1642 ············IPersistenceCapable pc = CheckPc(o);
1643 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
1644 ············{
1645 ················LoadState ls = pc.NDOLoadState;
1646 ················if (ls.FieldLoadState != null)
1647 ················{
1648 ····················if (ls.FieldLoadState[fieldOrdinal])
1649 ························return;
1650 ················}
1651 ················else
1652 ················{
1653 ····················ls.FieldLoadState = new BitArray( GetClass( pc ).Fields.Count() );
1654 ················}
1655 ················LoadData(o);
1656 ········}
1657 ········}
1658
1659 #pragma warning disable 419
1660 ········/// <summary>
1661 ········/// Load the data of a persistent object. This forces the transition of the object state from hollow to persistent.
1662 ········/// </summary>
1663 ········/// <param name="o">The hollow object.</param>
1664 ········/// <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>
1665 #pragma warning restore 419
1666 ········public void LoadData( object o )
1667 ········{
1668 ············LoadDataAsync( o ).ConfigureAwait( false ).GetAwaiter().GetResult();
1669 ········}
1670
1671 #pragma warning disable 419
1672 ········/// <summary>
1673 ········/// Load the data of a persistent object asynchronously. This forces the transition of the object state from hollow to persistent.
1674 ········/// </summary>
1675 ········/// <param name="o">The hollow object.</param>
1676 ········/// <param name="cancellationToken">A token to cancel the operation</param>
1677 ········/// <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>
1678 #pragma warning restore 419
1679 ········public virtual async Task LoadDataAsync( object o, CancellationToken cancellationToken = default )
1680 ········{
1681 ············using (EnterOperation())
1682 ············{
1683 ················await LoadDataInternalAsync( o, cancellationToken ).ConfigureAwait( false );
1684 ············}
1685 ········}
1686
1687 ········async Task LoadDataInternalAsync( object o, CancellationToken cancellationToken )
1688 ········{
1689 ············IPersistenceCapable pc = CheckPc(o);
1690 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Hollow, "Can only load hollow objects");
1691 ············if (pc.NDOObjectState != NDOObjectState.Hollow)
1692 ················return;
1693 ············Class cl = GetClass(pc);
1694 ············IQuery q;
1695 ············q = CreateOidQuery(pc, cl);
1696 ············cache.UpdateCache(pc); // Make sure the object is in the cache
1697
1698 ············var objects = await q.ExecuteAsync( cancellationToken ).ConfigureAwait( false );
1699 ············var count = objects.Count;
1700
1701 ············if (count > 1)
1702 ············{
1703 ················throw new NDOException( 72, "Load Data: " + count + " result objects with the same oid" );
1704 ············}
1705 ············else if (count == 0)
1706 ············{
1707 ················if (ObjectNotPresentEvent == null || !ObjectNotPresentEvent(pc))
1708 ················throw new NDOException( 72, "LoadData: Object " + pc.NDOObjectId.Dump() + " is not present in the database." );
1709 ············}
1710 ········}
1711
1712 ········/// <summary>
1713 ········/// Creates a new IQuery object for the given type
1714 ········/// </summary>
1715 ········/// <param name="t"></param>
1716 ········/// <param name="oql"></param>
1717 ········/// <param name="hollow"></param>
1718 ········/// <param name="queryLanguage"></param>
1719 ········/// <returns></returns>
1720 ········public IQuery NewQuery(Type t, string oql, bool hollow = false, QueryLanguage queryLanguage = QueryLanguage.NDOql)
1721 ········{
1722 ············Type template = typeof( NDOQuery<object> ).GetGenericTypeDefinition();
1723 ············Type qt = template.MakeGenericType( t );
1724 ············return (IQuery)Activator.CreateInstance( qt, this, oql, hollow, queryLanguage );
1725 ········}
1726
1727 ········private IQuery CreateOidQuery(IPersistenceCapable pc, Class cl)
1728 ········{
1729 ············ArrayList parameters = new ArrayList();
1730 ············string oql = "oid = {0}";
1731 ············IQuery q = NewQuery(pc.GetType(), oql, false);
1732 ············q.Parameters.Add( pc.NDOObjectId );
1733 ············q.AllowSubclasses = false;
1734 ············return q;
1735 ········}
1736
1737 ········/// <summary>
1738 ········/// Mark the object dirty. The current state is
1739 ········/// saved in a DataRow, which is stored in the DS. This is done, to allow easy rollback later. Also, the
1740 ········/// object is locked in the cache.
1741 ········/// </summary>
1742 ········/// <param name="pc"></param>
1743 ········internal virtual void MarkDirty(IPersistenceCapable pc)
1744 ········{
1745 ············if (pc.NDOObjectState != NDOObjectState.Persistent)
1746 ················return;
1747 ············SaveObjectState(pc);
1748 ············pc.NDOObjectState = NDOObjectState.PersistentDirty;
1749 ········}
1750
1751 ········/// <summary>
1752 ········/// Mark the object dirty, but make sure first, that the object is loaded.
1753 ········/// The current or loaded state is saved in a DataRow, which is stored in the DS.
1754 ········/// This is done, to allow easy rollback later. Also, the
1755 ········/// object is locked in the cache.
1756 ········/// </summary>
1757 ········/// <param name="pc"></param>
1758 ········internal void LoadAndMarkDirty(IPersistenceCapable pc)
1759 ········{
1760 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient, "Transient objects can't be marked as dirty.");
1761
1762 ············if(pc.NDOObjectState == NDOObjectState.Deleted)
1763 ············{
1764 ················throw new NDOException(73, "LoadAndMarkDirty: Access to deleted objects is not allowed.");
1765 ············}
1766
1767 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
1768 ················LoadData(pc);
1769
1770 ············// state is either (Created), Persistent, PersistentDirty
1771 ············if(pc.NDOObjectState == NDOObjectState.Persistent)
1772 ············{
1773 ················MarkDirty(pc);
1774 ············}
1775 ········}
1776
1777
1778
1779 ········/// <summary>
1780 ········/// Save current object state in DS and lock the object in the cache.
1781 ········/// The saved state can be used later to retrieve the original object value if the
1782 ········/// current transaction is aborted. Also the state of all relations (not related objects) is stored.
1783 ········/// </summary>
1784 ········/// <param name="pc">The object that should be saved</param>
1785 ········/// <param name="isDeleting">Determines, if the object is about being deletet.</param>
1786 ········/// <remarks>
1787 ········/// In a data row there are the following things:
1788 ········/// Item································Responsible for writing
1789 ········/// State (own, inherited, embedded)····WriteObject
1790 ········/// TimeStamp····························NDOPersistenceHandler
1791 ········/// Oid····································WriteId
1792 ········/// Foreign Keys and their Type Codes····WriteForeignKeys
1793 ········/// </remarks>
1794 ········protected virtual void SaveObjectState(IPersistenceCapable pc, bool isDeleting = false)
1795 ········{
1796 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Persistent, "Object must be unmodified and persistent but is " + pc.NDOObjectState);
1797 ············
1798 ············DataTable table = GetTable(pc);
1799 ············DataRow row = table.NewRow();
1800 ············Class cl = GetClass(pc);
1801 ············WriteObject(pc, row, cl.ColumnNames, 0);
1802 ············WriteIdToRow(pc, row);
1803 ············if (!isDeleting)
1804 ················WriteLostForeignKeysToRow(cl, pc, row);
1805 ············table.Rows.Add(row);
1806 ············row.AcceptChanges();
1807 ············
1808 ············var relations = CollectRelationStates(pc);
1809 ············cache.Lock(pc, row, relations);
1810 ········}
1811
1812 ········private void SaveFakeRow(IPersistenceCapable pc)
1813 ········{
1814 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Hollow, "Object must be hollow but is " + pc.NDOObjectState);
1815 ············
1816 ············DataTable table = GetTable(pc);
1817 ············DataRow row = table.NewRow();
1818 ············Class pcClass = GetClass(pc);
1819 ············row.SetColumnError(GetFakeRowOidColumnName(pcClass), hollowMarker);
1820 ············Class cl = GetClass(pc);
1821 ············//WriteObject(pc, row, cl.FieldNames, 0);
1822 ············WriteIdToRow(pc, row);
1823 ············table.Rows.Add(row);
1824 ············row.AcceptChanges();
1825 ············
1826 ············cache.Lock(pc, row, null);
1827 ········}
1828
1829 ········/// <summary>
1830 ········/// This defines one column of the row, in which we use the
1831 ········/// ColumnError property to determine, if the row is a fake row.
1832 ········/// </summary>
1833 ········/// <param name="pcClass"></param>
1834 ········/// <returns></returns>
1835 ········private string GetFakeRowOidColumnName(Class pcClass)
1836 ········{
1837 ············// In case of several OidColumns the first column defined in the mapping
1838 ············// will be the one, holding the fake row info.
1839 ············return ((OidColumn)pcClass.Oid.OidColumns[0]).Name;
1840 ········}
1841
1842 ········private bool IsFakeRow(Class cl, DataRow row)
1843 ········{
1844 ············return (row.GetColumnError(GetFakeRowOidColumnName(cl)) == hollowMarker);
1845 ········}
1846
1847 ········/// <summary>
1848 ········/// Make a list of objects persistent.
1849 ········/// </summary>
1850 ········/// <param name="list">the list of IPersistenceCapable objects</param>
1851 ········public void MakePersistent(System.Collections.IList list)
1852 ········{
1853 ············foreach (IPersistenceCapable pc in list)
1854 ············{
1855 ················MakePersistent(pc);
1856 ············}
1857 ········}
1858
1859 ········/// <summary>
1860 ········/// Save state of related objects in the cache. Only the list itself is duplicated and stored. The related objects are
1861 ········/// not duplicated.
1862 ········/// </summary>
1863 ········/// <param name="pc">the parent object of all relations</param>
1864 ········/// <returns></returns>
1865 ········protected internal virtual List<KeyValuePair<Relation,object>> CollectRelationStates(IPersistenceCapable pc)
1866 ········{
1867 ············// Save state of relations
1868 ············Class c = GetClass(pc);
1869 ············List<KeyValuePair<Relation, object>> relations = new List<KeyValuePair<Relation, object>>( c.Relations.Count());
1870 ············foreach(Relation r in c.Relations)
1871 ············{
1872 ················if (r.Multiplicity == RelationMultiplicity.Element)
1873 ················{
1874 ····················relations.Add( new KeyValuePair<Relation, object>( r, mappings.GetRelationField( pc, r.FieldName ) ) );
1875 ················}
1876 ················else
1877 ················{
1878 ····················IList l = mappings.GetRelationContainer(pc, r);
1879 ····················if(l != null)
1880 ····················{
1881 ························l = (IList) ListCloner.CloneList(l);
1882 ····················}
1883 ····················relations.Add( new KeyValuePair<Relation, object>( r, l ) );
1884 ················}
1885 ············}
1886
1887 ············return relations;
1888 ········}
1889
1890
1891 ········/// <summary>
1892 ········/// Restore the saved relations.··Note that the objects are not restored as this is handled transparently
1893 ········/// by the normal persistence mechanism. Only the number and order of objects are restored, e.g. the state,
1894 ········/// the list had at the beginning of the transaction.
1895 ········/// </summary>
1896 ········/// <param name="pc"></param>
1897 ········/// <param name="relations"></param>
1898 ········private void RestoreRelatedObjects(IPersistenceCapable pc, List<KeyValuePair<Relation, object>> relations )
1899 ········{
1900 ············Class c = GetClass(pc);
1901
1902 ············foreach(var entry in relations)
1903 ············{
1904 ················var r = entry.Key;
1905 ················if (r.Multiplicity == RelationMultiplicity.Element)
1906 ················{
1907 ····················mappings.SetRelationField(pc, r.FieldName, entry.Value);
1908 ················}
1909 ················else
1910 ················{
1911 ····················if (pc.NDOGetLoadState(r.Ordinal))
1912 ····················{
1913 ························// Help GC by clearing lists
1914 ························IList l = mappings.GetRelationContainer(pc, r);
1915 ························if(l != null)
1916 ························{
1917 ····························l.Clear();
1918 ························}
1919 ························// Restore relation
1920 ························mappings.SetRelationContainer(pc, r, (IList)entry.Value);
1921 ····················}
1922 ················}
1923 ············}
1924 ········}
1925
1926
1927 ········/// <summary>
1928 ········/// Generates a query for related objects without mapping table.
1929 ········/// Note: this function can't be called in polymorphic scenarios,
1930 ········/// since they need a mapping table.
1931 ········/// </summary>
1932 ········/// <returns></returns>
1933 ········async Task<IList> QueryRelatedObjectsAsync( IPersistenceCapable pc, Relation r, IList l, bool hollow, CancellationToken cancellationToken )
1934 ········{
1935 ············// At this point of execution we know,
1936 ············// that the target type is not polymorphic and is not 1:1.
1937
1938 ············// We can't fetch these objects with an NDOql query
1939 ············// since this would require a relation in the opposite direction
1940
1941 ············IList relatedObjects;
1942 ············if (l != null)
1943 ················relatedObjects = l;
1944 ············else
1945 ················relatedObjects = mappings.CreateRelationContainer( pc, r );
1946
1947 ············Type t = r.ReferencedType;
1948 ············Class cl = GetClass( t );
1949 ············var provider = cl.Provider;
1950
1951 ············StringBuilder sb = new StringBuilder("SELECT * FROM ");
1952 ············var relClass = GetClass( r.ReferencedType );
1953 ············sb.Append( GetClass( r.ReferencedType ).GetQualifiedTableName() );
1954 ············sb.Append( " WHERE " );
1955 ············int i = 0;
1956 ············List<object> parameters = new List<object>();
1957 ············new ForeignKeyIterator( r ).Iterate( delegate ( ForeignKeyColumn fkColumn, bool isLastElement )
1958 ·············· {
1959 ·················· sb.Append( fkColumn.GetQualifiedName(relClass) );
1960 ·················· sb.Append( " = {" );
1961 ·················· sb.Append(i);
1962 ·················· sb.Append( '}' );
1963 ·················· parameters.Add( pc.NDOObjectId.Id[i] );
1964 ·················· if (!isLastElement)
1965 ······················ sb.Append( " AND " );
1966 ·················· i++;
1967 ·············· } );
1968
1969 ············if (!(String.IsNullOrEmpty( r.ForeignKeyTypeColumnName )))
1970 ············{
1971 ················sb.Append( " AND " );
1972 ················sb.Append( provider.GetQualifiedTableName( relClass.TableName + "." + r.ForeignKeyTypeColumnName ) );
1973 ················sb.Append( " = " );
1974 ················sb.Append( pc.NDOObjectId.Id.TypeId );
1975 ············}
1976
1977 ············IQuery q = NewQuery( t, sb.ToString(), hollow, Query.QueryLanguage.Sql );
1978
1979 ············foreach (var p in parameters)
1980 ············{
1981 ················q.Parameters.Add( p );
1982 ············}
1983
1984 ············q.AllowSubclasses = false;··// Remember: polymorphic relations always have a mapping table
1985
1986 ············IList l2 = await q.ExecuteAsync( cancellationToken ).ConfigureAwait( false );
1987
1988 ············foreach (object o in l2)
1989 ················relatedObjects.Add( o );
1990
1991 ············return relatedObjects;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1992 ········}
1993
 
 
 
 
 
 
 
 
 
1994
1995 ········/// <summary>
1996 ········/// Resolves an relation. The loaded objects will be hollow.
1997 ········/// </summary>
1998 ········/// <param name="o">The parent object.</param>
1999 ········/// <param name="fieldName">The field name of the container or variable, which represents the relation.</param>
2000 ········/// <param name="hollow">True, if the fetched objects should be hollow.</param>
2001 ········/// <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>
2002 ········public void LoadRelation(object o, string fieldName, bool hollow)
2003 ········{
2004 ············LoadRelationAsync( o, fieldName, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
2005 ········}
2006
2007 ········/// <summary>
2008 ········/// Resolves an relation asynchronously.
2009 ········/// </summary>
2010 ········/// <param name="o">The parent object.</param>
2011 ········/// <param name="fieldName">The field name of the container or variable, which represents the relation.</param>
2012 ········/// <param name="hollow">True, if the fetched objects should be hollow.</param>
2013 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2014 ········/// <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>
2015 ········public virtual async Task LoadRelationAsync( object o, string fieldName, bool hollow, CancellationToken cancellationToken = default )
2016 ········{
2017 ············using (EnterOperation())
2018 ············{
2019 ················IPersistenceCapable pc = CheckPc(o);
2020 ················await LoadRelationInternalAsync( pc, fieldName, hollow, cancellationToken ).ConfigureAwait( false );
2021 ············}
2022 ········}
2023
2024 ········
2025
2026 ········internal IList LoadRelation(IPersistenceCapable pc, Relation r, bool hollow)
2027 ········{
2028 ············return LoadRelationAsync( pc, r, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
2029 ········}
2030
2031 ········internal async Task<IList> LoadRelationAsync( IPersistenceCapable pc, Relation r, bool hollow, CancellationToken cancellationToken = default )
2032 ········{
2033 ············using (EnterOperation())
2034 ············{
2035 ················return await LoadRelationCoreAsync( pc, r, hollow, cancellationToken ).ConfigureAwait( false );
2036 ············}
2037 ········}
2038
2039 ········async Task<IList> LoadRelationCoreAsync( IPersistenceCapable pc, Relation r, bool hollow, CancellationToken cancellationToken )
2040 ········{
2041 ············IList result = null;
2042
2043 ············if (pc.NDOObjectState == NDOObjectState.Created)
2044 ················return null;
2045
2046 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
2047 ················await LoadDataAsync( pc, cancellationToken ).ConfigureAwait( false );
2048
2049 ············if(r.MappingTable == null)
2050 ············{
2051 ················// 1:1 are loaded with LoadData
2052 ················if (r.Multiplicity == RelationMultiplicity.List)
2053 ················{
2054 ····················// Help GC by clearing lists
2055 ····················IList l = mappings.GetRelationContainer(pc, r);
2056 ····················if(l != null)
2057 ························l.Clear();
2058 ····················IList relatedObjects = await QueryRelatedObjectsAsync( pc, r, l, hollow, cancellationToken ).ConfigureAwait( false );
2059 ····················mappings.SetRelationContainer(pc, r, relatedObjects);
2060 ····················result = relatedObjects;
2061 ················}
2062 ············}
2063 ············else
2064 ············{
2065 ················DataTable dt = null;
2066
2067 ················using (IMappingTableHandler handler = PersistenceHandlerManager.GetPersistenceHandler( pc ).GetMappingTableHandler( r ))
2068 ················{
2069 ····················await CheckTransactionAsync( handler, r.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2070 ····················dt = await handler.FindRelatedObjectsAsync( pc.NDOObjectId, this.ds, cancellationToken ).ConfigureAwait( false );
2071 ················}
2072
2073 ················IList relatedObjects;
2074 ················if(r.Multiplicity == RelationMultiplicity.Element)
2075 ····················relatedObjects = GenericListReflector.CreateList(r.ReferencedType, dt.Rows.Count);
2076 ················else
2077 ················{
2078 ····················relatedObjects = mappings.GetRelationContainer(pc, r);
2079 ····················if(relatedObjects != null)
2080 ························relatedObjects.Clear();··// Objects will be reread
2081 ····················else
2082 ························relatedObjects = mappings.CreateRelationContainer(pc, r);
2083 ················}
2084 ····················
2085 ················foreach(DataRow objRow in dt.Rows)
2086 ················{
2087 ····················Type relType;
2088
2089 ····················if (r.MappingTable.ChildForeignKeyTypeColumnName != null)························
2090 ····················{
2091 ························object typeCodeObj = objRow[r.MappingTable.ChildForeignKeyTypeColumnName];
2092 ························if (typeCodeObj is System.DBNull)
2093 ····························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() ) );
2094 ························relType = typeManager[(int)typeCodeObj];
2095 ························if (relType == null)
2096 ····························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));
2097 ····················}························
2098 ····················else
2099 ····················{
2100 ························relType = r.ReferencedType;
2101 ····················}
2102
2103 ····················//TODO: Generic Types: Exctract the type description from the type name column
2104 ····················if (relType.IsGenericTypeDefinition)
2105 ························throw new NotImplementedException("NDO doesn't support relations to generic types via mapping tables.");
2106 ····················ObjectId id = ObjectIdFactory.NewObjectId(relType, GetClass(relType), objRow, r.MappingTable, this.typeManager);
2107 ····················IPersistenceCapable relObj = FindObject(id);
2108 ····················relatedObjects.Add(relObj);
2109 ················}····
2110 ················if (r.Multiplicity == RelationMultiplicity.Element)
2111 ················{
2112 ····················Debug.Assert(relatedObjects.Count <= 1, "NDO retrieved more than one object for relation with cardinality 1");
2113 ····················mappings.SetRelationField(pc, r.FieldName, relatedObjects.Count > 0 ? relatedObjects[0] : null);
2114 ················}
2115 ················else
2116 ················{
2117 ····················mappings.SetRelationContainer(pc, r, relatedObjects);
2118 ····················result = relatedObjects;
2119 ················}
2120 ············}
2121 ············// Mark relation as loaded
2122 ············pc.NDOSetLoadState(r.Ordinal, true);
2123 ············return result;
2124 ········}
2125
2126 ········/// <summary>
2127 ········/// Loads elements of a relation
2128 ········/// </summary>
2129 ········/// <param name="pc">The object which needs to load the relation</param>
2130 ········/// <param name="relationName">The name of the relation</param>
2131 ········/// <param name="hollow">Determines, if the related objects should be hollow.</param>
2132 ········internal IList LoadRelationInternal(IPersistenceCapable pc, string relationName, bool hollow)
2133 ········{
2134 ············return LoadRelationInternalAsync( pc, relationName, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
2135 ········}
2136
2137 ········internal async Task<IList> LoadRelationInternalAsync( IPersistenceCapable pc, string relationName, bool hollow, CancellationToken cancellationToken = default )
2138 ········{
2139 ············if (pc.NDOObjectState == NDOObjectState.Created)
2140 ················return null;
2141 ············Class cl = GetClass(pc);
2142
2143 ············Relation r = cl.FindRelation(relationName);
2144
2145 ············if ( r == null )
2146 ················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 ) );
2147
2148 ············if ( pc.NDOGetLoadState( r.Ordinal ) )
2149 ················return null;
2150
2151 ············return await LoadRelationAsync( pc, r, hollow, cancellationToken ).ConfigureAwait( false );
2152 ········}
2153
2154 ········/// <summary>
2155 ········/// Load the related objects of a parent object. The current value of the relation is replaced by the
2156 ········/// a list of objects that has been read from the DB.
2157 ········/// </summary>
2158 ········/// <param name="pc">The parent object of the relations</param>
2159 ········/// <param name="row">A data row containing the state of the object</param>
2160 ········private void LoadRelated1To1Objects(IPersistenceCapable pc, DataRow row)
2161 ········{
2162 ············// Stripped down to only serve 1:1-Relations w/out mapping table
2163 ············Class cl = GetClass(pc);
2164 ············foreach(Relation r in cl.Relations)
2165 ············{
2166 ················if(r.MappingTable == null)
2167 ················{
2168 ····················if (r.Multiplicity == RelationMultiplicity.Element)
2169 ····················{
2170 ························bool isNull = false;
2171 ························foreach (ForeignKeyColumn fkColumn in r.ForeignKeyColumns)
2172 ························{
2173 ····························isNull = isNull || (row[fkColumn.Name] == DBNull.Value);
2174 ························}
2175 ························if (isNull)
2176 ························{
2177 ····························mappings.SetRelationField(pc, r.FieldName, null);
2178 ························}
2179 ························else
2180 ························{
2181 ····························Type relType;
2182 ····························if (r.HasSubclasses)
2183 ····························{
2184 ································object o = row[r.ForeignKeyTypeColumnName];
2185 ································if (o == DBNull.Value)
2186 ····································throw new NDOException(75, String.Format(
2187 ········································"Can't resolve subclass type code {0} of type {1} - type code value is DBNull.",
2188 ········································row[r.ForeignKeyTypeColumnName], r.ReferencedTypeName));
2189 ································relType = typeManager[(int)o];
2190 ····························}
2191 ····························else
2192 ····························{
2193 ································relType = r.ReferencedType;
2194 ····························}
2195 ····························if (relType == null)
2196 ····························{
2197 ································throw new NDOException(75, String.Format(
2198 ····································"Can't resolve subclass type code {0} of type {1} - check, if your mapping file is correct.",
2199 ····································row[r.ForeignKeyTypeColumnName], r.ReferencedTypeName));
2200 ····························}
2201 ····
2202 ····························int count = r.ForeignKeyColumns.Count();
2203 ····························object[] keydata = new object[count];
2204 ····························int i = 0;
2205 ····························foreach(ForeignKeyColumn fkColumn in r.ForeignKeyColumns)
2206 ····························{
2207 ································keydata[i++] = row[fkColumn.Name];
2208 ····························}
2209
2210 ····························Type oidType = relType;
2211 ····························if (oidType.IsGenericTypeDefinition)
2212 ································oidType = mappings.GetRelationFieldType(r);
2213
2214 ····························ObjectId childOid = ObjectIdFactory.NewObjectId(oidType, GetClass(relType), keydata, this.typeManager);
2215 ····························if(childOid.IsValid())
2216 ································mappings.SetRelationField(pc, r.FieldName, FindObject(childOid));
2217 ····························else
2218 ································mappings.SetRelationField(pc, r.FieldName, null);
2219
2220 ························}
2221 ························pc.NDOSetLoadState(r.Ordinal, true);
2222 ····················}
2223 ················}
2224 ············}
2225 ········}
2226
2227 ········
2228 ········/// <summary>
2229 ········/// Creates a new ObjectId with the same Key value as a given ObjectId.
2230 ········/// </summary>
2231 ········/// <param name="oid">An ObjectId, which Key value will be used to build the new ObjectId.</param>
2232 ········/// <param name="t">The type of the object, the id will belong to.</param>
2233 ········/// <returns>An object of type ObjectId, or ObjectId.InvalidId</returns>
2234 ········/// <remarks>If the type t doesn't have a mapping in the mapping file an Exception of type NDOException is thrown.</remarks>
2235 ········public ObjectId NewObjectId(ObjectId oid, Type t)
2236 ········{
2237 ············return new ObjectId(oid.Id, t);
2238 ········}
2239
2240 ········/*
2241 ········/// <summary>
2242 ········/// Creates a new ObjectId which can be used to retrieve objects from the database.
2243 ········/// </summary>
2244 ········/// <param name="keyData">The id, which will be used to search for the object in the database</param>
2245 ········/// <param name="t">The type of the object.</param>
2246 ········/// <returns>An object of type ObjectId, or ObjectId.InvalidId</returns>
2247 ········/// <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>
2248 ········public ObjectId NewObjectId(object keyData, Type t)
2249 ········{
2250 ············if (keyData == null || keyData == DBNull.Value)
2251 ················return ObjectId.InvalidId;
2252
2253 ············Class cl =··GetClass(t);············
2254 ············
2255 ············if (cl.Oid.FieldType == typeof(int))
2256 ················return new ObjectId(new Int32Key(t, (int)keyData));
2257 ············else if (cl.Oid.FieldType == typeof(string))
2258 ················return new ObjectId(new StringKey(t, (String) keyData));
2259 ············else if (cl.Oid.FieldType == typeof(Guid))
2260 ················if (keyData is string)
2261 ····················return new ObjectId(new GuidKey(t, new Guid((String) keyData)));
2262 ················else
2263 ····················return new ObjectId(new GuidKey(t, (Guid) keyData));
2264 ············else if (cl.Oid.FieldType == typeof(MultiKey))
2265 ················return new ObjectId(new MultiKey(t, (object[]) keyData));
2266 ············else
2267 ················return ObjectId.InvalidId;
2268 ········}
2269 ········*/
2270
2271
2272 ········/*
2273 ········ * ····················if (cl.Oid.FieldName != null && HasOwnerCreatedIds)
2274 ····················{
2275 ························// The column, which hold the oid gets overwritten, if
2276 ························// Oid.FieldName contains a value.
2277 */
2278 ········private void WriteIdFieldsToRow(IPersistenceCapable pc, DataRow row)
2279 ········{
2280 ············Class cl = GetClass(pc);
2281
2282 ············if (cl.Oid.IsDependent)
2283 ················return;
2284
2285 ············Key key = pc.NDOObjectId.Id;
2286
2287 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2288 ············{
2289 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2290 ················if (oidColumn.FieldName != null)
2291 ················{
2292 ····················row[oidColumn.Name] = key[i];
2293 ················}
2294 ············}
2295 ········}
2296
2297 ········private void WriteIdToRow(IPersistenceCapable pc, DataRow row)
2298 ········{
2299 ············NDO.Mapping.Class cl = GetClass(pc);
2300 ············ObjectId oid = pc.NDOObjectId;
2301
2302 ············if (cl.TimeStampColumn != null)
2303 ················row[cl.TimeStampColumn] = pc.NDOTimeStamp;
2304
2305 ············if (cl.Oid.IsDependent)··// Oid data is in relation columns
2306 ················return;
2307
2308 ············Key key = oid.Id;
2309
2310 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2311 ············{
2312 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2313 ················row[oidColumn.Name] = key[i];
2314 ············}
2315 ········}
2316
2317 ········private void ReadIdFromRow(IPersistenceCapable pc, DataRow row)
2318 ········{
2319 ············ObjectId oid = pc.NDOObjectId;
2320 ············NDO.Mapping.Class cl = GetClass(pc);
2321
2322 ············if (cl.Oid.IsDependent)··// Oid data is in relation columns
2323 ················return;
2324
2325 ············Key key = oid.Id;
2326
2327 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2328 ············{
2329 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2330 ················object o = row[oidColumn.Name];
2331 ················if (!(o is Int32) && !(o is Guid) && !(o is String) && !(o is Int64))
2332 ····················throw new NDOException(78, "ReadId: invalid Id Column type in " + oidColumn.Name + ": " + o.GetType().FullName);
2333 ················if (oidColumn.SystemType == typeof(Guid) && (o is String))
2334 ····················key[i] = new Guid((string)o);
2335 ················else
2336 ····················key[i] = o;
2337 ············}
2338
2339 ········}
2340
2341 ········private void ReadId (Cache.Entry e)
2342 ········{
2343 ············ReadIdFromRow(e.pc, e.row);
2344 ········}
2345
2346 ········private void WriteObject(IPersistenceCapable pc, DataRow row, string[] fieldNames)
2347 ········{
2348 ············WriteObject(pc, row, fieldNames, 0);
2349 ········}
2350
2351 ········private void ReadTimeStamp(Class cl, IPersistenceCapable pc, DataRow row)
2352 ········{
2353 ············if (cl.TimeStampColumn == null)
2354 ················return;
2355 ············object col = row[cl.TimeStampColumn];
2356 ············if (col is String)
2357 ················pc.NDOTimeStamp = new Guid(col.ToString());
2358 ············else
2359 ················pc.NDOTimeStamp = (Guid) col;
2360 ········}
2361
2362
2363
2364 ········private void ReadTimeStamp(Cache.Entry e)
2365 ········{
2366 ············IPersistenceCapable pc = e.pc;
2367 ············NDO.Mapping.Class cl = GetClass(pc);
2368 ············Debug.Assert(!IsFakeRow(cl, e.row));
2369 ············if (cl.TimeStampColumn == null)
2370 ················return;
2371 ············if (e.row[cl.TimeStampColumn] is String)
2372 ················e.pc.NDOTimeStamp = new Guid(e.row[cl.TimeStampColumn].ToString());
2373 ············else
2374 ················e.pc.NDOTimeStamp = (Guid) e.row[cl.TimeStampColumn];
2375 ········}
2376
2377 ········/// <summary>
2378 ········/// Determines, if any objects are new, changed or deleted.
2379 ········/// </summary>
2380 ········public virtual bool HasChanges
2381 ········{
2382 ············get
2383 ············{
2384 ················return cache.LockedObjects.Count > 0;
2385 ············}
2386 ········}
2387
2388 ········/// <summary>
2389 ········/// Do the update for all rows in the ds.
2390 ········/// </summary>
2391 ········/// <param name="types">Types with changes.</param>
2392 ········/// <param name="delete">True, if delete operations are to be performed.</param>
2393 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2394 ········/// <remarks>
2395 ········/// Delete and Insert/Update operations are to be separated to maintain the type order.
2396 ········/// </remarks>
2397 ········private async Task UpdateTypesAsync( IList types, bool delete, CancellationToken cancellationToken )
2398 ········{
2399 ············foreach(Type t in types)
2400 ············{
2401 ················//Debug.WriteLine("Update Deleted Objects: "··+ t.Name);
2402 ················using (IPersistenceHandler handler = PersistenceHandlerManager.GetPersistenceHandler( t ))
2403 ················{
2404 ····················await CheckTransactionAsync( handler, t, cancellationToken ).ConfigureAwait( false );
2405 ····················ConcurrencyErrorHandler ceh = new ConcurrencyErrorHandler(this.OnConcurrencyError);
2406 ····················handler.ConcurrencyError += ceh;
2407 ····················try
2408 ····················{
2409 ························DataTable dt = GetTable(t);
2410 ························if (delete)
2411 ····························await handler.UpdateDeletedObjectsAsync( dt, cancellationToken ).ConfigureAwait( false );
2412 ························else
2413 ····························await handler.UpdateAsync( dt, cancellationToken ).ConfigureAwait( false );
2414 ····················}
2415 ····················finally
2416 ····················{
2417 ························handler.ConcurrencyError -= ceh;
2418 ····················}
2419 ················}
2420 ············}
2421 ········}
2422
2423 ········internal async Task UpdateCreatedMappingTableEntriesAsync( CancellationToken cancellationToken )
2424 ········{
2425 ············foreach (MappingTableEntry e in createdMappingTableObjects)
2426 ············{
2427 ················if (!e.DeleteEntry)
2428 ····················WriteMappingTableEntry(e);
2429 ············}
2430 ············// Now update all mapping tables
2431 ············foreach (IMappingTableHandler handler in mappingHandler.Values)
2432 ············{
2433 ················await CheckTransactionAsync( handler, handler.Relation.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2434 ················await handler.UpdateAsync( ds, cancellationToken ).ConfigureAwait( false );
2435 ············}
2436 ········}
2437
2438 ········internal async Task UpdateDeletedMappingTableEntriesAsync( CancellationToken cancellationToken )
2439 ········{
2440 ············foreach (MappingTableEntry e in createdMappingTableObjects)
2441 ············{
2442 ················if (e.DeleteEntry)
2443 ····················WriteMappingTableEntry(e);
2444 ············}
2445 ············// Now update all mapping tables
2446 ············foreach (IMappingTableHandler handler in mappingHandler.Values)
2447 ············{
2448 ················await CheckTransactionAsync( handler, handler.Relation.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2449 ················await handler.UpdateAsync( ds, cancellationToken ).ConfigureAwait( false );
2450 ············}
2451 ········}
2452
2453 ········/// <summary>
2454 ········/// Save all changed object into the DataSet and update the DB.
2455 ········/// When a newly created object is written to DB, the key might change. Therefore,
2456 ········/// the id is updated and the object is removed and re-inserted into the cache.
2457 ········/// </summary>
2458 ········public void Save(bool deferCommit = false)
2459 ········{
2460 ············SaveAsync( deferCommit ).ConfigureAwait( false ).GetAwaiter().GetResult();
2461 ········}
2462
2463 ········/// <summary>
2464 ········/// Save all changed object into the DataSet and update the DB asynchronously.
2465 ········/// When a newly created object is written to DB, the key might change. Therefore,
2466 ········/// the id is updated and the object is removed and re-inserted into the cache.
2467 ········/// </summary>
2468 ········/// <param name="deferCommit">Determines, if the commit of the transaction should be deferred.</param>
2469 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2470 ········/// <remarks>
2471 ········/// User callbacks like CollisionEvent and OnSavedEvent might be called on a thread pool thread.
2472 ········/// </remarks>
2473 ········public virtual async Task SaveAsync( bool deferCommit = false, CancellationToken cancellationToken = default )
2474 ········{
2475 ············using (EnterOperation())
2476 ············{
2477 ················await SaveInternalAsync( deferCommit, cancellationToken ).ConfigureAwait( false );
2478 ············}
2479 ········}
2480
2481 ········async Task SaveInternalAsync( bool deferCommit, CancellationToken cancellationToken )
2482 ········{
2483 ············if (IsClosed)
2484 ················throw new ObjectDisposedException(GetType().Name);
2485
2486 ············this.DeferredMode = deferCommit;
2487 ············var htOnSaving = new HashSet<ObjectId>();
2488 ············for(;;)
2489 ············{
2490 ················// We need to work on a copy of the locked objects list,
2491 ················// since the handlers might add more objects to the cache
2492 ················var lockedObjects = cache.LockedObjects.ToList();
2493 ················int count = lockedObjects.Count;
2494 ················foreach(Cache.Entry e in lockedObjects)
2495 ················{
2496 ····················if (e.pc.NDOObjectState != NDOObjectState.Deleted)
2497 ····················{
2498 ························IPersistenceNotifiable ipn = e.pc as IPersistenceNotifiable;
2499 ························if (ipn != null)
2500 ························{
2501 ····························if (!htOnSaving.Contains(e.pc.NDOObjectId))
2502 ····························{
2503 ································ipn.OnSaving();
2504 ································htOnSaving.Add(e.pc.NDOObjectId);
2505 ····························}
2506 ························}
2507 ····················}
2508 ················}
2509 ················// The system is stable, if the count doesn't change
2510 ················if (cache.LockedObjects.Count == count)
2511 ····················break;
2512 ············}
2513
2514 ············if (this.OnSavingEvent != null)
2515 ············{
2516 ················IList onSavingObjects = new ArrayList(cache.LockedObjects.Count);
2517 ················foreach(Cache.Entry e in cache.LockedObjects)
2518 ····················onSavingObjects.Add(e.pc);
2519 ················OnSavingEvent(onSavingObjects);
2520 ············}
2521
2522 ············List<Type> types = new List<Type>();
2523 ············List<IPersistenceCapable> deletedObjects = new List<IPersistenceCapable>();
2524 ············List<IPersistenceCapable> hollowModeObjects = hollowMode ? new List<IPersistenceCapable>() : null;
2525 ············List<IPersistenceCapable> changedObjects = new List<IPersistenceCapable>();
2526 ············List<IPersistenceCapable> addedObjects = new List<IPersistenceCapable>();
2527 ············List<Cache.Entry> addedCacheEntries = new List<Cache.Entry>();
2528
2529 ············// Save current state in DataSet
2530 ············foreach (Cache.Entry e in cache.LockedObjects)
2531 ············{
2532 ················Type objType = e.pc.GetType();
2533
2534 ················if (objType.IsGenericType && !objType.IsGenericTypeDefinition)
2535 ····················objType = objType.GetGenericTypeDefinition();
2536
2537 ················Class cl = GetClass(e.pc);
2538 ················//Debug.WriteLine("Saving: " + objType.Name + " id = " + e.pc.NDOObjectId.Dump());
2539 ················if(!types.Contains(objType))
2540 ················{
2541 ····················//Debug.WriteLine("Added··type " + objType.Name);
2542 ····················types.Add(objType);
2543 ················}
2544 ················NDOObjectState objectState = e.pc.NDOObjectState;
2545 ················if(objectState == NDOObjectState.Deleted)
2546 ················{
2547 ····················deletedObjects.Add(e.pc);
2548 ················}
2549 ················else if(objectState == NDOObjectState.Created)
2550 ················{
2551 ····················WriteObject(e.pc, e.row, cl.ColumnNames);····················
2552 ····················WriteIdFieldsToRow(e.pc, e.row);··// If fields are mapped to Oid, write them into the row
2553 ····················WriteForeignKeysToRow(e.pc, e.row);
2554 ····················//····················Debug.WriteLine(e.pc.GetType().FullName);
2555 ····················//····················DataRow[] rows = new DataRow[cache.LockedObjects.Count];
2556 ····················//····················i = 0;
2557 ····················//····················foreach(Cache.Entry e2 in cache.LockedObjects)
2558 ····················//····················{
2559 ····················//························rows[i++] = e2.row;
2560 ····················//····················}
2561 ····················//····················System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("testCommand");
2562 ····················//····················new SqlDumper(new DebugLogAdapter(), NDOProviderFactory.Instance["Sql"], cmd, cmd, cmd, cmd).Dump(rows);
2563
2564 ····················addedCacheEntries.Add(e);
2565 ····················addedObjects.Add( e.pc );
2566 ····················//····················objectState = NDOObjectState.Persistent;
2567 ················}
2568 ················else
2569 ················{
2570 ····················if (e.pc.NDOObjectState == NDOObjectState.PersistentDirty)
2571 ························changedObjects.Add( e.pc );
2572 ····················WriteObject(e.pc, e.row, cl.ColumnNames);
2573 ····················WriteForeignKeysToRow(e.pc, e.row); ····················
2574 ················}
2575 ················if(hollowMode && (objectState == NDOObjectState.Persistent || objectState == NDOObjectState.Created || objectState == NDOObjectState.PersistentDirty) )
2576 ················{
2577 ····················hollowModeObjects.Add(e.pc);
2578 ················}
2579 ············}
2580
2581 ············// Before we delete any db rows, we have to make sure, to delete mapping
2582 ············// table entries first, which might have relations to the db rows to be deleted
2583 ············await UpdateDeletedMappingTableEntriesAsync( cancellationToken ).ConfigureAwait( false );
2584
2585 ············// Update DB
2586 ············if (ds.HasChanges())
2587 ············{
2588
2589 ················// We need the reversed update order for deletions.
2590 ················types.Sort( ( t1, t2 ) =>
2591 ················{
2592 ····················int i1 = mappings.GetUpdateOrder( t1 );
2593 ····················int i2 = mappings.GetUpdateOrder( t2 );
2594 ····················if (i1 < i2)
2595 ····················{
2596 ························if (!addedObjects.Any( pc => pc.GetType() == t1 ))
2597 ····························i1 += 100000;
2598 ····················}
2599 ····················else
2600 ····················{
2601 ························if (!addedObjects.Any( pc => pc.GetType() == t2 ))
2602 ····························i2 += 100000;
2603 ····················}
2604 ····················return i2 - i1;
2605 ················} );
2606
2607 ················// Delete records first
2608
2609 ················await UpdateTypesAsync( types, true, cancellationToken ).ConfigureAwait( false );
2610
2611 ················// Now do all other updates in correct order.
2612 ················types.Reverse();
2613
2614 ················await UpdateTypesAsync( types, false, cancellationToken ).ConfigureAwait( false );
2615 ················
2616 ················ds.AcceptChanges();
2617 ················if(createdDirectObjects.Count > 0)
2618 ················{
2619 ····················// Rewrite all children that have foreign keys to parents which have just been saved now.
2620 ····················// They must be written again to store the correct foreign keys.
2621 ····················foreach(IPersistenceCapable pc in createdDirectObjects)
2622 ····················{
2623 ························Class cl = GetClass(pc);
2624 ························DataRow r = this.cache.GetDataRow(pc);
2625 ························string fakeColumnName = GetFakeRowOidColumnName(cl);
2626 ························object o = r[fakeColumnName];
2627 ························r[fakeColumnName] = o;
2628 ····················}
2629
2630 ····················await UpdateTypesAsync( types, false, cancellationToken ).ConfigureAwait( false );
2631 ················}
2632
2633 ················// Because object id might have changed during DB insertion, re-register newly created objects in the cache.
2634 ················foreach(Cache.Entry e in addedCacheEntries)
2635 ················{
2636 ····················cache.DeregisterLockedObject(e.pc);
2637 ····················ReadId(e);
2638 ····················cache.RegisterLockedObject(e.pc, e.row, e.relations);
2639 ················}
2640
2641 ················// Now update all mapping tables. Because of possible subclasses, there is no
2642 ················// relation between keys in the dataset schema. Therefore, we can update mapping
2643 ················// tables only after all other objects have been written to ensure correct foreign keys.
2644 ················await UpdateCreatedMappingTableEntriesAsync( cancellationToken ).ConfigureAwait( false );
2645
2646 ················// The rows may contain now new Ids, which should be
2647 ················// stored in the lostRowInfo's before the rows get detached
2648 ················foreach(Cache.Entry e in cache.LockedObjects)
2649 ················{
2650 ····················if (e.row.RowState != DataRowState.Detached)
2651 ····················{
2652 ························IPersistenceCapable pc = e.pc;
2653 ························ReadLostForeignKeysFromRow(GetClass(pc), pc, e.row);
2654 ····················}
2655 ················}
2656
2657 ················ds.AcceptChanges();
2658 ············}
2659
2660 ············await EndSaveAsync( !deferCommit, cancellationToken ).ConfigureAwait( false );
2661
2662 ············foreach(IPersistenceCapable pc in deletedObjects)
2663 ············{
2664 ················MakeObjectTransient(pc, false);
2665 ············}
2666
2667 ············ds.Clear();
2668 ············mappingHandler.Clear();
2669 ············createdDirectObjects.Clear();
2670 ············createdMappingTableObjects.Clear();
2671 ············this.relationChanges.Clear();
2672
2673 ············if(hollowMode)
2674 ············{
2675 ················MakeHollow(hollowModeObjects);
2676 ············}
2677
2678 ············if (this.OnSavedEvent != null)
2679 ············{
2680 ················AuditSet auditSet = new AuditSet()
2681 ················{
2682 ····················ChangedObjects = changedObjects,
2683 ····················CreatedObjects = addedObjects,
2684 ····················DeletedObjects = deletedObjects
2685 ················};
2686 ················this.OnSavedEvent( auditSet );
2687 ············}
2688 ········}
2689
2690 ········private async Task EndSaveAsync( bool forceCommit, CancellationToken cancellationToken )
2691 ········{
2692 ············foreach(Cache.Entry e in cache.LockedObjects)
2693 ············{
2694 ················if (e.pc.NDOObjectState == NDOObjectState.Created || e.pc.NDOObjectState == NDOObjectState.PersistentDirty)
2695 ····················this.ReadTimeStamp(e);
2696 ················e.pc.NDOObjectState = NDOObjectState.Persistent;
2697 ············}
2698
2699 ············cache.UnlockAll();
2700
2701 ············await CheckEndTransactionAsync( forceCommit, cancellationToken ).ConfigureAwait( false );
2702 ········}
2703
2704 ········/// <summary>
2705 ········/// Write all foreign keys for 1:1-relations.
2706 ········/// </summary>
2707 ········/// <param name="pc">The persistent object.</param>
2708 ········/// <param name="pcRow">The DataRow of the pesistent object.</param>
2709 ········private void WriteForeignKeysToRow(IPersistenceCapable pc, DataRow pcRow)
2710 ········{
2711 ············foreach(Relation r in mappings.Get1to1Relations(pc.GetType()))
2712 ············{
2713 ················IPersistenceCapable relObj = (IPersistenceCapable)mappings.GetRelationField(pc, r.FieldName);
2714 ················bool isDependent = GetClass(pc).Oid.IsDependent;
2715
2716 ················if ( relObj != null )
2717 ················{
2718 ····················int i = 0;
2719 ····················foreach ( ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2720 ····················{
2721 ························pcRow[fkColumn.Name] = relObj.NDOObjectId.Id[i++];
2722 ····················}
2723 ····················if ( r.ForeignKeyTypeColumnName != null )
2724 ····················{
2725 ························pcRow[r.ForeignKeyTypeColumnName] = relObj.NDOObjectId.Id.TypeId;
2726 ····················}
2727 ················}
2728 ················else
2729 ················{
2730 ····················foreach ( ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2731 ····················{
2732 ························pcRow[fkColumn.Name] = DBNull.Value;
2733 ····················}
2734 ····················if ( r.ForeignKeyTypeColumnName != null )
2735 ····················{
2736 ························pcRow[r.ForeignKeyTypeColumnName] = DBNull.Value;
2737 ····················}
2738 ················}
2739 ············}
2740 ········}
2741
2742
2743
2744 ········/// <summary>
2745 ········/// Write a mapping table entry to it's corresponding table. This is a pair of foreign keys.
2746 ········/// </summary>
2747 ········/// <param name="e">the mapping table entry</param>
2748 ········private void WriteMappingTableEntry(MappingTableEntry e)
2749 ········{
2750 ············IPersistenceCapable pc = e.ParentObject;
2751 ············IPersistenceCapable relObj = e.RelatedObject;
2752 ············Relation r = e.Relation;
2753 ············DataTable dt = GetTable(r.MappingTable.TableName);
2754 ············DataRow row = dt.NewRow();
2755 ············int i = 0;
2756 ············foreach (ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2757 ············{
2758 ················row[fkColumn.Name] = pc.NDOObjectId.Id[i++];
2759 ············}
2760 ············i = 0;
2761 ············foreach (ForeignKeyColumn fkColumn in r.MappingTable.ChildForeignKeyColumns)
2762 ············{
2763 ················row[fkColumn.Name] = relObj.NDOObjectId.Id[i++];
2764 ············}
2765
2766 ············if (r.ForeignKeyTypeColumnName != null)
2767 ················row[r.ForeignKeyTypeColumnName] = pc.NDOObjectId.Id.TypeId;
2768 ············if (r.MappingTable.ChildForeignKeyTypeColumnName != null)
2769 ················row[r.MappingTable.ChildForeignKeyTypeColumnName] = relObj.NDOObjectId.Id.TypeId;
2770
2771 ············dt.Rows.Add(row);
2772 ············if(e.DeleteEntry)
2773 ············{
2774 ················row.AcceptChanges();
2775 ················row.Delete();
2776 ············}
2777
2778 ············IMappingTableHandler handler;
2779 ············if (!mappingHandler.TryGetValue( r, out handler ))
2780 ············{
2781 ················mappingHandler[r] = handler = PersistenceHandlerManager.GetPersistenceHandler( pc ).GetMappingTableHandler( r );
2782 ············}
2783 ········}
2784
2785
2786 ········/// <summary>
2787 ········/// Undo changes of a certain object
2788 ········/// </summary>
2789 ········/// <param name="o">Object to undo</param>
2790 ········public void Restore(object o)
2791 ········{············
2792 ············IPersistenceCapable pc = CheckPc(o);
2793 ············Cache.Entry e = null;
2794 ············foreach (Cache.Entry entry in cache.LockedObjects)
2795 ············{
2796 ················if (entry.pc == pc)
2797 ················{
2798 ····················e = entry;
2799 ····················break;
2800 ················}
2801 ············}
2802 ············if (e == null)
2803 ················return;
2804 ············Class cl = GetClass(e.pc);
2805 ············switch (pc.NDOObjectState)
2806 ············{
2807 ················case NDOObjectState.PersistentDirty:
2808 ····················ObjectListManipulator.Remove(createdDirectObjects, pc);
2809 ····················foreach(Relation r in cl.Relations)
2810 ····················{
2811 ························if (r.Multiplicity == RelationMultiplicity.Element)
2812 ························{
2813 ····························IPersistenceCapable subPc = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
2814 ····························if (subPc != null && cache.IsLocked(subPc))
2815 ································Restore(subPc);
2816 ························}
2817 ························else
2818 ························{
2819 ····························if (!pc.NDOGetLoadState(r.Ordinal))
2820 ································continue;
2821 ····························IList subList = (IList) mappings.GetRelationContainer(pc, r);
2822 ····························if (subList != null)
2823 ····························{
2824 ································foreach(IPersistenceCapable subPc2 in subList)
2825 ································{
2826 ····································if (cache.IsLocked(subPc2))
2827 ········································Restore(subPc2);
2828 ································}
2829 ····························}
2830 ························}
2831 ····················}
2832 ····················RestoreRelatedObjects(pc, e.relations);
2833 ····················e.row.RejectChanges();
2834 ····················ReadObject(pc, e.row, cl.ColumnNames, 0);
2835 ····················cache.Unlock(pc);
2836 ····················pc.NDOObjectState = NDOObjectState.Persistent;
2837 ····················break;
2838 ················case NDOObjectState.Created:
2839 ····················ReadObject(pc, e.row, cl.ColumnNames, 0);
2840 ····················cache.Unlock(pc);
2841 ····················MakeObjectTransient(pc, true);
2842 ····················break;
2843 ················case NDOObjectState.Deleted:
2844 ····················if (!this.IsFakeRow(cl, e.row))
2845 ····················{
2846 ························e.row.RejectChanges();
2847 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2848 ························e.pc.NDOObjectState = NDOObjectState.Persistent;
2849 ····················}
2850 ····················else
2851 ····················{
2852 ························e.row.RejectChanges();
2853 ························e.pc.NDOObjectState = NDOObjectState.Hollow;
2854 ····················}
2855 ····················cache.Unlock(pc);
2856 ····················break;
2857
2858 ············}
2859 ········}
2860
2861 ········/// <summary>
2862 ········/// Aborts a pending transaction without restoring the object state.
2863 ········/// </summary>
2864 ········/// <remarks>Supports both local and EnterpriseService Transactions.</remarks>
2865 ········public void AbortTransaction()
2866 ········{
2867 ············AbortTransactionAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
2868 ········}
2869
2870 ········/// <summary>
2871 ········/// Aborts a pending transaction asynchronously without restoring the object state.
2872 ········/// </summary>
2873 ········/// <remarks>The rollback can't be canceled, therefore there is no CancellationToken.</remarks>
2874 ········public virtual async Task AbortTransactionAsync()
2875 ········{
2876 ············await TransactionScope.DisposeAsync().ConfigureAwait( false );
2877 ········}
2878
2879 ········/// <summary>
2880 ········/// Rejects all changes and restores the original object state. Added Objects will be made transient.
2881 ········/// </summary>
2882 ········public void Abort()
2883 ········{
2884 ············AbortAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
2885 ········}
2886
2887 ········/// <summary>
2888 ········/// Rejects all changes and restores the original object state asynchronously. Added Objects will be made transient.
2889 ········/// </summary>
2890 ········/// <remarks>The rollback can't be canceled, therefore there is no CancellationToken.</remarks>
2891 ········public virtual async Task AbortAsync()
2892 ········{
2893 ············// RejectChanges of the DS cannot be called because newly added rows would be deleted,
2894 ············// and therefore, couldn't be restored. Instead we call RejectChanges() for each
2895 ············// individual row.
2896 ············createdDirectObjects.Clear();
2897 ············createdMappingTableObjects.Clear();
2898 ············ArrayList deletedObjects = new ArrayList();
2899 ············ArrayList hollowModeObjects = hollowMode ? new ArrayList() : null;
2900
2901 ············// Read all objects from DataSet
2902 ············foreach (Cache.Entry e in cache.LockedObjects)
2903 ············{
2904 ················//Debug.WriteLine("Reading: " + e.pc.GetType().Name);
2905
2906 ················Class cl = GetClass(e.pc);
2907 ················bool isFakeRow = this.IsFakeRow(cl, e.row);
2908 ················if (!isFakeRow)
2909 ················{
2910 ····················RestoreRelatedObjects(e.pc, e.relations);
2911 ················}
2912 ················else
2913 ················{
2914 ····················Debug.Assert(e.pc.NDOObjectState == NDOObjectState.Deleted, "Fake row objects can only exist in deleted state");
2915 ················}
2916
2917 ················switch(e.pc.NDOObjectState)
2918 ················{
2919 ····················case NDOObjectState.Created:
2920 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2921 ························deletedObjects.Add(e.pc);
2922 ························break;
2923
2924 ····················case NDOObjectState.PersistentDirty:
2925 ························e.row.RejectChanges();
2926 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2927 ························e.pc.NDOObjectState = NDOObjectState.Persistent;
2928 ························break;
2929
2930 ····················case NDOObjectState.Deleted:
2931 ························if (!isFakeRow)
2932 ························{
2933 ····························e.row.RejectChanges();
2934 ····························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2935 ····························e.pc.NDOObjectState = NDOObjectState.Persistent;
2936 ························}
2937 ························else
2938 ························{
2939 ····························e.row.RejectChanges();
2940 ····························e.pc.NDOObjectState = NDOObjectState.Hollow;
2941 ························}
2942 ························break;
2943
2944 ····················default:
2945 ························throw new InternalException(2082, "Abort(): wrong state detected: " + e.pc.NDOObjectState + " id = " + e.pc.NDOObjectId.Dump());
2946 ························//Debug.Assert(false, "Object with wrong state detected: " + e.pc.NDOObjectState);
2947 ························//break;
2948 ················}
2949 ················if(hollowMode && e.pc.NDOObjectState == NDOObjectState.Persistent)
2950 ················{
2951 ····················hollowModeObjects.Add(e.pc);
2952 ················}
2953 ············}
2954 ············cache.UnlockAll();
2955 ············foreach(IPersistenceCapable pc in deletedObjects)
2956 ············{
2957 ················MakeObjectTransient(pc, true);
2958 ············}
2959 ············ds.Clear();
2960 ············mappingHandler.Clear();
2961 ············if(hollowMode)
2962 ············{
2963 ················MakeHollow(hollowModeObjects);
2964 ············}
2965
2966 ············this.relationChanges.Clear();
2967
2968
2969 ············await AbortTransactionAsync().ConfigureAwait( false );
2970 ········}
2971
2972
2973 ········/// <summary>
2974 ········/// Reset object to its transient state and remove it from the cache. Optinally, remove the object id to
2975 ········/// disable future access.
2976 ········/// </summary>
2977 ········/// <param name="pc"></param>
2978 ········/// <param name="removeId">Indicates if the object id should be nulled</param>
2979 ········private void MakeObjectTransient(IPersistenceCapable pc, bool removeId)
2980 ········{
2981 ············cache.Deregister(pc);
2982 ············// MakeTransient doesn't remove the ID, because delete makes objects transient and we need the id for the ChangeLog············
2983 ············if(removeId)
2984 ············{
2985 ················pc.NDOObjectId = null;
2986 ············}
2987 ············pc.NDOObjectState = NDOObjectState.Transient;
2988 ············pc.NDOStateManager = null;
2989 ········}
2990
2991 ········/// <summary>
2992 ········/// Makes an object transient.
2993 ········/// The object can be used afterwards, but changes will not be saved in the database.
2994 ········/// </summary>
2995 ········/// <remarks>
2996 ········/// Only persistent or hollow objects can be detached. Hollow objects are loaded to ensure valid data.
2997 ········/// </remarks>
2998 ········/// <param name="o">The object to detach.</param>
2999 ········public void MakeTransient(object o)
3000 ········{
3001 ············IPersistenceCapable pc = CheckPc(o);
3002 ············if(pc.NDOObjectState != NDOObjectState.Persistent && pc.NDOObjectState··!= NDOObjectState.Hollow)
3003 ············{
3004 ················throw new NDOException(79, "MakeTransient: Illegal state '" + pc.NDOObjectState + "' for this operation");
3005 ············}
3006
3007 ············if(pc.NDOObjectState··== NDOObjectState.Hollow)
3008 ············{
3009 ················LoadData(pc);
3010 ············}
3011 ············MakeObjectTransient(pc, true);
3012 ········}
3013
3014
3015 ········/// <summary>
3016 ········/// Make all objects of a list transient.
3017 ········/// </summary>
3018 ········/// <param name="list">the list of transient objects</param>
3019 ········public void MakeTransient(System.Collections.IList list)
3020 ········{
3021 ············foreach (IPersistenceCapable pc in list)
3022 ················MakeTransient(pc);
3023 ········}
3024
3025 ········/// <summary>
3026 ········/// Remove an object from the DB. Note that the object itself is not destroyed and may still be used.
3027 ········/// </summary>
3028 ········/// <param name="o">The object to remove</param>
3029 ········public void Delete(object o)
3030 ········{
3031 ············IPersistenceCapable pc = CheckPc(o);
3032 ············if (pc.NDOObjectState == NDOObjectState.Transient)
3033 ············{
3034 ················throw new NDOException( 120, "Can't delete transient object" );
3035 ············}
3036 ············if (pc.NDOObjectState != NDOObjectState.Deleted)
3037 ············{
3038 ················Delete(pc, true);
3039 ············}
3040 ········}
3041
3042
3043 ········private void LoadAllRelations(object o)
3044 ········{
3045 ············IPersistenceCapable pc = CheckPc(o);
3046 ············Class cl = GetClass(pc);
3047 ············foreach(Relation r in cl.Relations)
3048 ············{
3049 ················if (!pc.NDOGetLoadState(r.Ordinal))
3050 ····················LoadRelation(pc, r, true);
3051 ············}
3052 ········}
3053
3054
3055 ········/// <summary>
3056 ········/// Remove an object from the DB. Note that the object itself is not destroyed and may still be used.
3057 ········/// </summary>
3058 ········/// <remarks>
3059 ········/// If checkAssoziations it true, the object cannot be deleted if it is part of a bidirectional assoziation.
3060 ········/// This is the case if delete was called from user code. Internally, an object may be deleted because it is called from
3061 ········/// the parent object.
3062 ········/// </remarks>
3063 ········/// <param name="pc">the object to remove</param>
3064 ········/// <param name="checkAssoziations">true if child of a composition can't be deleted</param>
3065 ········private void Delete(IPersistenceCapable pc, bool checkAssoziations)
3066 ········{
3067 ············//Debug.WriteLine("Delete " + pc.NDOObjectId.Dump());
3068 ············//Debug.Indent();
3069 ············IDeleteNotifiable idn = pc as IDeleteNotifiable;
3070 ············if (idn != null)
3071 ················idn.OnDelete();
3072
3073 ············LoadAllRelations(pc);
3074 ············DeleteRelatedObjects(pc, checkAssoziations);
3075
3076 ············switch(pc.NDOObjectState)
3077 ············{
3078 ················case NDOObjectState.Transient:
3079 ····················throw new NDOException(80, "Cannot delete transient object: " + pc.NDOObjectId);
3080
3081 ················case NDOObjectState.Created:
3082 ····················DataRow row = cache.GetDataRow(pc);
3083 ····················row.Delete();
3084 ····················ArrayList cdosToDelete = new ArrayList();
3085 ····················foreach (IPersistenceCapable cdo in createdDirectObjects)
3086 ························if ((object)cdo == (object)pc)
3087 ····························cdosToDelete.Add(cdo);
3088 ····················foreach (object o in cdosToDelete)
3089 ························ObjectListManipulator.Remove(createdDirectObjects, o);
3090 ····················MakeObjectTransient(pc, true);
3091 ····················break;
3092 ················case NDOObjectState.Persistent:
3093 ····················if (!cache.IsLocked(pc)) // Deletes k�nnen durchaus mehrmals aufgerufen werden
3094 ························SaveObjectState(pc, true);
3095 ····················row = cache.GetDataRow(pc);
3096 ····················row.Delete();
3097 ····················pc.NDOObjectState = NDOObjectState.Deleted;
3098 ····················break;
3099 ················case NDOObjectState.Hollow:
3100 ····················if (!cache.IsLocked(pc)) // Deletes k�nnen durchaus mehrmals aufgerufen werden
3101 ························SaveFakeRow(pc);
3102 ····················row = cache.GetDataRow(pc);
3103 ····················row.Delete();
3104 ····················pc.NDOObjectState = NDOObjectState.Deleted;
3105 ····················break;
3106
3107 ················case NDOObjectState.PersistentDirty:
3108 ····················row = cache.GetDataRow(pc);
3109 ····················row.Delete();
3110 ····················pc.NDOObjectState··= NDOObjectState.Deleted;
3111 ····················break;
3112
3113 ················case NDOObjectState.Deleted:
3114 ····················break;
3115 ············}
3116
3117 ············//Debug.Unindent();
3118 ········}
3119
3120
3121 ········/// <summary>
3122 ········/// Finds the pending entry, which inserts or deletes the row of the mapping table for the given objects.
3123 ········/// </summary>
3124 ········/// <remarks>
3125 ········/// Both relations of a bidirectional n:m relation use the same mapping table.
3126 ········/// So an entry created through the foreign relation describes the same row.
3127 ········/// </remarks>
3128 ········private MappingTableEntry FindMappingTableEntry(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
3129 ········{
3130 ············foreach(MappingTableEntry e in createdMappingTableObjects)
3131 ············{
3132 ················if (e.Relation == r && e.ParentObject == pc && e.RelatedObject == relObj)
3133 ····················return e;
3134 ················if (r.Bidirectional && e.Relation == r.ForeignRelation && e.ParentObject == relObj && e.RelatedObject == pc)
3135 ····················return e;
3136 ············}
3137 ············return null;
3138 ········}
3139
3140 ········/// <summary>
3141 ········/// Makes sure, that an object is added only once to a relation with a mapping table.
3142 ········/// </summary>
3143 ········/// <remarks>
3144 ········/// The mapping table has a unique index on the columns of both sides. A second entry would fail while saving.
3145 ········/// </remarks>
3146 ········private void CheckDuplicateMappingTableEntry(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
3147 ········{
3148 ············MappingTableEntry mte = FindMappingTableEntry(pc, r, relObj);
3149 ············bool isDuplicate;
3150 ············if (mte != null)
3151 ············{
3152 ················isDuplicate = !mte.DeleteEntry;
3153 ············}
3154 ············else
3155 ············{
3156 ················// The relation list contains the objects of the existing rows. If one of the objects is created,
3157 ················// a row can't exist and the list might contain relObj already, because MakePersistent adds the objects of the list.
3158 ················isDuplicate = r.Multiplicity == RelationMultiplicity.List
3159 ····················&& pc.NDOObjectState != NDOObjectState.Created
3160 ····················&& relObj.NDOObjectState != NDOObjectState.Created
3161 ····················&& pc.NDOGetLoadState(r.Ordinal)
3162 ····················&& mappings.GetRelationContainer(pc, r) is IList l
3163 ····················&& ObjectListManipulator.Contains(l, relObj);
3164 ············}
3165
3166 ············if (isDuplicate)
3167 ················throw new NDOException(123, "The object " + relObj.NDOObjectId.Dump() + " is already part of the relation " + pc.GetType().FullName + "." + r.FieldName + " of the object " + pc.NDOObjectId.Dump() + ". An object can't be added twice to a relation with a mapping table.");
3168 ········}
3169
3170 ········private void DeleteMappingTableEntry(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3171 ········{
3172 ············MappingTableEntry mte = FindMappingTableEntry(pc, r, child);
3173
3174 ············if (mte != null)
3175 ············{
3176 ················// Removing an object, which was added in the same transaction, cancels the insertion.
3177 ················if (!mte.DeleteEntry)
3178 ····················createdMappingTableObjects.Remove(mte);
3179 ············}
3180 ············else if (pc.NDOObjectState != NDOObjectState.Created && child.NDOObjectState != NDOObjectState.Created)
3181 ············{
3182 ················createdMappingTableObjects.Add(new MappingTableEntry(pc, child, r, true));
3183 ············}
3184 ········}
3185
3186 ········private void DeleteOrNullForeignRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3187 ········{
3188 ············// Two tasks: a) Null the foreign key
3189 ············//··············b) remove the element from the foreign container
3190
3191 ············if (!r.Bidirectional)
3192 ················return;
3193
3194 ············// this keeps the oid valid
3195 ············if (GetClass(child.GetType()).Oid.IsDependent)
3196 ················return;
3197
3198 ············if(r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
3199 ············{
3200 ················LoadAndMarkDirty(child);
3201 ················mappings.SetRelationField(child, r.ForeignRelation.FieldName, null);
3202 ············}
3203 ············else //if(r.Multiplicity == RelationMultiplicity.List &&
3204 ················// r.ForeignRelation.Multiplicity == RelationMultiplicity.List)··
3205 ············{
3206 ················if (!child.NDOGetLoadState(r.ForeignRelation.Ordinal))
3207 ····················LoadRelation(child, r.ForeignRelation, true);
3208 ················IList l = mappings.GetRelationContainer(child, r.ForeignRelation);
3209 ················if (l == null)
3210 ····················throw new NDOException(67, "Can't remove object from the list " + child.GetType().FullName + "." + r.ForeignRelation.FieldName + ". The list is null.");
3211 ················ObjectListManipulator.Remove(l, pc);
3212 ················// Don't need to delete the mapping table entry, because that was done
3213 ················// through the parent.
3214 ············}
3215 ········}
3216
3217 ········private void DeleteOrNullRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3218 ········{
3219 ············// 1) Element····nomap····ass
3220 ············// 2) Element····nomap····comp
3221 ············// 3) Element····map········ass
3222 ············// 4) Element····map········comp
3223 ············// 5) List········nomap····ass
3224 ············// 6) List········nomap····comp
3225 ············// 7) List········map········ass
3226 ············// 8) List········map········comp
3227
3228 ············// Two tasks: Null foreign key and, if Composition, delete the child
3229
3230 ············// If Mapping Table, delete the entry - 3,7
3231 ············// If List and assoziation, null the foreign key in the foreign class - 5
3232 ············// If Element, null the foreign key in the own class 1,2,3,4
3233 ············// If composition, delete the child 2,4,6,8
3234
3235 ············// If the relObj is newly created
3236 ············ObjectListManipulator.Remove(createdDirectObjects, child);
3237 ············Class childClass = GetClass(child);
3238
3239 ············if (r.MappingTable != null)··// 3,7
3240 ············{················
3241 ················DeleteMappingTableEntry(pc, r, child);
3242 ············}
3243 ············else if (r.Multiplicity == RelationMultiplicity.List
3244 ················&& !r.Composition && !childClass.Oid.IsDependent) // 5
3245 ············{················
3246 ················LoadAndMarkDirty(child);
3247 ················DataRow row = this.cache.GetDataRow(child);
3248 ················foreach (ForeignKeyColumn fkColumnn in r.ForeignKeyColumns)
3249 ················{
3250 ····················row[fkColumnn.Name] = DBNull.Value;
3251 ····················child.NDOLoadState.ReplaceRowInfo(fkColumnn.Name, DBNull.Value);
3252 ················}
3253 ············}
3254 ············else if (r.Multiplicity == RelationMultiplicity.Element) // 1,2,3,4
3255 ············{
3256 ················LoadAndMarkDirty(pc);
3257 ············}
3258 ············if (r.Composition || childClass.Oid.IsDependent)
3259 ············{
3260 #if DEBUG
3261 ················if (child.NDOObjectState == NDOObjectState.Transient)
3262 ····················Debug.WriteLine("***** Object shouldn't be transient: " + child.GetType().FullName);
3263 #endif
3264 ················// Deletes the foreign key in case of List multiplicity
3265 ················// In case of Element multiplicity, the parent is either deleted,
3266 ················// or RemoveRelatedObject is called because the relation has been nulled.
3267 ················Delete(child);··
3268 ············}
3269 ········}
3270
3271 ········/// <summary>
3272 ········/// Remove a related object
3273 ········/// </summary>
3274 ········/// <param name="pc"></param>
3275 ········/// <param name="r"></param>
3276 ········/// <param name="child"></param>
3277 ········/// <param name="calledFromStateManager"></param>
3278 ········protected virtual void InternalRemoveRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable child, bool calledFromStateManager)
3279 ········{
3280 ············//TODO: We need a relation management, which is independent of
3281 ············//the state management of an object. At the moment the relation
3282 ············//lists or elements are cached for restore, if an object is marked dirty.
3283 ············//Thus we have to mark dirty our parent object in any case at the moment.
3284 ············if (calledFromStateManager)
3285 ················MarkDirty(pc);
3286
3287 ············// Object can be deleted in an OnDelete-Handler
3288 ············if (child.NDOObjectState == NDOObjectState.Deleted)
3289 ················return;
3290 ············//············Debug.WriteLine("InternalRemoveRelatedObject " + pc.GetType().Name + " " + r.FieldName + " " + child.GetType());
3291 ············// Preconditions
3292 ············// This is called either by DeleteRelatedObjects or by RemoveRelatedObject
3293 ············// The Object state is checked there
3294
3295 ············// If there is a composition in the opposite direction
3296 ············// && the other direction hasn't been processed
3297 ············// throw an exception.
3298 ············// If an exception is thrown at this point, have a look at IsLocked....
3299 ············if (r.Bidirectional && r.ForeignRelation.Composition
3300 ················&& !removeLock.IsLocked(child, r.ForeignRelation, pc))
3301 ················throw new NDOException(82, "Cannot remove related object " + child.GetType().FullName + " from parent " + pc.NDOObjectId.Dump() + ". Object must be removed through the parent.");
3302
3303 ············if (!removeLock.GetLock(pc, r, child))
3304 ················return;
3305
3306 ············try
3307 ············{
3308 ················// must be in this order, since the child
3309 ················// can be deleted in DeleteOrNullRelation
3310 ················//if (changeForeignRelations)
3311 ················DeleteOrNullForeignRelation(pc, r, child);
3312 ················DeleteOrNullRelation(pc, r, child);
3313 ············}
3314 ············finally
3315 ············{
3316 ················removeLock.Unlock(pc, r, child);
3317 ············}
3318
3319 ············this.relationChanges.Add( new RelationChangeRecord( pc, child, r.FieldName, false ) );
3320 ········}
3321
3322 ········private void DeleteRelatedObjects2(IPersistenceCapable pc, Class parentClass, bool checkAssoziations, Relation r)
3323 ········{
3324 ············//············Debug.WriteLine("DeleteRelatedObjects2 " + pc.GetType().Name + " " + r.FieldName);
3325 ············//············Debug.Indent();
3326 ············if (r.Multiplicity == RelationMultiplicity.Element)
3327 ············{
3328 ················IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
3329 ················if(child != null)
3330 ················{
3331 ····················//····················if(checkAssoziations && r.Bidirectional && !r.Composition)
3332 ····················//····················{
3333 ····················//························if (!r.ForeignRelation.Composition)
3334 ····················//························{
3335 ····················//····························mappings.SetRelationField(pc, r.FieldName, null);
3336 ····················//····························mappings.SetRelationField(child, r.ForeignRelation.FieldName, null);
3337 ····················//························}
3338 ····················//····························//System.Diagnostics.Debug.WriteLine("Nullen: pc = " + pc.GetType().Name + " child = " + child.GetType().Name);
3339 ····················//························else
3340 ····················//····························throw new NDOException(83, "Can't remove object of type " + pc.GetType().FullName + "; It is contained by an object of type " + child.GetType().FullName);
3341 ····················//····················}
3342 ····················InternalRemoveRelatedObject(pc, r, child, false);
3343 ················}
3344 ············}
3345 ············else
3346 ············{
3347 ················IList list = mappings.GetRelationContainer(pc, r);
3348 ················if(list != null && list.Count > 0)
3349 ················{
3350 ····················//····················if(checkAssoziations && r.Bidirectional && !r.Composition)
3351 ····················//····················{
3352 ····················//························throw new xxNDOException(84, "Cannot delete object " + pc.NDOObjectId + " in an assoziation. Remove related objects first.");
3353 ····················//····················}
3354 ····················// Since RemoveRelatedObjects probably changes the list,
3355 ····················// we iterate through a copy of the list.
3356 ····················ArrayList al = new ArrayList(list);
3357 ····················foreach(IPersistenceCapable relObj in al)
3358 ····················{
3359 ························InternalRemoveRelatedObject(pc, r, relObj, false);
3360 ····················}
3361 ················}
3362 ············}
3363 ············//············Debug.Unindent();
3364 ········}
3365
3366 ········/// <summary>
3367 ········/// Remove all related objects from a parent.
3368 ········/// </summary>
3369 ········/// <param name="pc">the parent object</param>
3370 ········/// <param name="checkAssoziations"></param>
3371 ········private void DeleteRelatedObjects(IPersistenceCapable pc, bool checkAssoziations)
3372 ········{
3373 ············//············Debug.WriteLine("DeleteRelatedObjects " + pc.NDOObjectId.Dump());
3374 ············//············Debug.Indent();
3375 ············// delete all related objects:
3376 ············Class parentClass = GetClass(pc);
3377 ············// Remove Assoziations first
3378 ············foreach(Relation r in parentClass.Relations)
3379 ············{
3380 ················if (!r.Composition)
3381 ····················DeleteRelatedObjects2(pc, parentClass, checkAssoziations, r);
3382 ············}
3383 ············foreach(Relation r in parentClass.Relations)
3384 ············{
3385 ················if (r.Composition)
3386 ····················DeleteRelatedObjects2(pc, parentClass, checkAssoziations, r);
3387 ············}
3388
3389 ············//············Debug.Unindent();
3390 ········}
3391
3392 ········/// <summary>
3393 ········/// Delete a list of objects
3394 ········/// </summary>
3395 ········/// <param name="list">the list of objects to remove</param>
3396 ········public void Delete(IList list)
3397 ········{
3398 ············for (int i = 0; i < list.Count; i++)
3399 ············{
3400 ················IPersistenceCapable pc = (IPersistenceCapable) list[i];
3401 ················Delete(pc);
3402 ············}
3403 ········}
3404
3405 ········/// <summary>
3406 ········/// Make object hollow. All relations will be unloaded and object data will be
3407 ········/// newly fetched during the next touch of a persistent field.
3408 ········/// </summary>
3409 ········/// <param name="o"></param>
3410 ········public virtual void MakeHollow(object o)
3411 ········{
3412 ············IPersistenceCapable pc = CheckPc(o);
3413 ············MakeHollow(pc, false);
3414 ········}
3415
3416 ········/// <summary>
3417 ········/// Make the object hollow if it is persistent. Unload all complex data.
3418 ········/// </summary>
3419 ········/// <param name="o"></param>
3420 ········/// <param name="recursive">if true then unload related objects as well</param>
3421 ········public virtual void MakeHollow(object o, bool recursive)
3422 ········{
3423 ············IPersistenceCapable pc = CheckPc(o);
3424 ············if(pc.NDOObjectState == NDOObjectState.Hollow)
3425 ················return;
3426 ············if(pc.NDOObjectState != NDOObjectState.Persistent)
3427 ············{
3428 ················throw new NDOException(85, "MakeHollow: Illegal state for this operation (" + pc.NDOObjectState.ToString() + ")");
3429 ············}
3430 ············pc.NDOObjectState = NDOObjectState.Hollow;
3431 ············MakeRelationsHollow(pc, recursive);
3432 ········}
3433
3434 ········/// <summary>
3435 ········/// Make all objects of a list hollow.
3436 ········/// </summary>
3437 ········/// <param name="list">the list of objects that should be made hollow</param>
3438 ········public virtual void MakeHollow(System.Collections.IList list)
3439 ········{
3440 ············MakeHollow(list, false);
3441 ········}
3442
3443 ········/// <summary>
3444 ········/// Make all objects of a list hollow.
3445 ········/// </summary>
3446 ········/// <param name="list">the list of objects that should be made hollow</param>
3447 ········/// <param name="recursive">if true then unload related objects as well</param>
3448 ········public void MakeHollow(System.Collections.IList list, bool recursive)
3449 ········{
3450 ············foreach (IPersistenceCapable pc in list)
3451 ················MakeHollow(pc, recursive);················
3452 ········}
3453
3454 ········/// <summary>
3455 ········/// Make all unlocked objects in the cache hollow.
3456 ········/// </summary>
3457 ········public virtual void MakeAllHollow()
3458 ········{
3459 ············foreach(var pc in cache.UnlockedObjects)
3460 ············{
3461 ················MakeHollow(pc, false);
3462 ············}
3463 ········}
3464
3465 ········/// <summary>
3466 ········/// Make relations hollow.
3467 ········/// </summary>
3468 ········/// <param name="pc">The parent object</param>
3469 ········/// <param name="recursive">If true, the function unloads related objects as well.</param>
3470 ········private void MakeRelationsHollow(IPersistenceCapable pc, bool recursive)
3471 ········{
3472 ············Class c = GetClass(pc);
3473 ············foreach(Relation r in c.Relations)
3474 ············{
3475 ················if (r.Multiplicity == RelationMultiplicity.Element)
3476 ················{
3477 ····················mappings.SetRelationField(pc, r.FieldName, null);
3478 ····················//····················IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
3479 ····················//····················if((null != child) && recursive)
3480 ····················//····················{
3481 ····················//························MakeHollow(child, true);
3482 ····················//····················}
3483 ················}
3484 ················else
3485 ················{
3486 ····················if (!pc.NDOGetLoadState(r.Ordinal))
3487 ························continue;
3488 ····················// Help GC by clearing lists
3489 ····················IList l = mappings.GetRelationContainer(pc, r);
3490 ····················if(l != null)
3491 ····················{
3492 ························if(recursive)
3493 ························{
3494 ····························MakeHollow(l, true);
3495 ························}
3496 ························l.Clear();
3497 ····················}
3498 ····················// Hollow relation
3499 ····················mappings.SetRelationContainer(pc, r, null);
3500 ················}
3501 ············}
3502 ············ClearRelationState(pc);
3503 ········}
3504
3505 ········private void ClearRelationState(IPersistenceCapable pc)
3506 ········{
3507 ············Class cl = GetClass(pc);
3508 ············foreach(Relation r in cl.Relations)
3509 ················pc.NDOSetLoadState(r.Ordinal, false);
3510 ········}
3511
3512 ········private void SetRelationState(IPersistenceCapable pc)
3513 ········{
3514 ············Class cl = GetClass(pc);
3515 ············// Due to a bug in the enhancer the constructors are not always patched right,
3516 ············// so NDOLoadState might be uninitialized
3517 ············if (pc.NDOLoadState == null)
3518 ············{
3519 ················FieldInfo fi = new BaseClassReflector(pc.GetType()).GetField("_ndoLoadState", BindingFlags.Instance | BindingFlags.NonPublic);
3520 ················if (fi == null)
3521 ····················throw new InternalException(3131, "pm.SetRelationState: No FieldInfo for _ndoLoadState");
3522 ················fi.SetValue(pc, new LoadState());
3523 ············}
3524
3525 ············// After serialization the relation load state is null
3526 ············if (pc.NDOLoadState.RelationLoadState == null)
3527 ················pc.NDOLoadState.RelationLoadState = new BitArray(LoadState.RelationLoadStateSize);
3528 ············foreach(Relation r in cl.Relations)
3529 ················pc.NDOSetLoadState(r.Ordinal, true);
3530 ········}
3531
3532 ········/// <summary>
3533 ········/// Creates an object of a given type and resolves constructor parameters using the container.
3534 ········/// </summary>
3535 ········/// <param name="t">The type of the persistent object</param>
3536 ········/// <returns></returns>
3537 ········public IPersistenceCapable CreateObject(Type t)
3538 ········{
3539 ············return (IPersistenceCapable) ActivatorUtilities.CreateInstance( ServiceProvider, t );
3540 ········}
3541
3542 ········/// <summary>
3543 ········/// Creates an object of a given type and resolves constructor parameters using the container.
3544 ········/// </summary>
3545 ········/// <typeparam name="T">The type of the object to create.</typeparam>
3546 ········/// <returns></returns>
3547 ········public T CreateObject<T>()
3548 ········{
3549 ············return (T)CreateObject( typeof( T ) );
3550 ········}
3551
3552 ········/// <summary>
3553 ········/// Finds an object in the object cache and loads the object from the database
3554 ········/// in case of a cache miss.
3555 ········/// </summary>
3556 ········/// <param name="shortId"></param>
3557 ········/// <returns>A persistent object</returns>
3558 ········public async Task <IPersistenceCapable> GetObjectByShortIdAsync(string shortId)
3559 ········{
3560 ············var pc = FindObject(shortId);
3561 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
3562 ················await LoadDataAsync( pc ).ConfigureAwait(false);
3563 ············return pc;
3564 ········}
3565
3566 ········/// <summary>
3567 ········/// Gets the requested object. It first builds an ObjectId using the type and the
3568 ········/// key data. Then it uses FindObject to retrieve the object. No database access
3569 ········/// is performed.
3570 ········/// </summary>
3571 ········/// <param name="t">The type of the object to retrieve.</param>
3572 ········/// <param name="keyData">The key value to build the object id.</param>
3573 ········/// <returns>A hollow object</returns>
3574 ········/// <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>
3575 ········public IPersistenceCapable FindObject(Type t, object keyData)
3576 ········{
3577 ············ObjectId oid = ObjectIdFactory.NewObjectId(t, GetClass(t), keyData, this.typeManager);
3578 ············return FindObject(oid);
3579 ········}
3580
3581 ········/// <summary>
3582 ········/// Finds an object using a short id.
3583 ········/// </summary>
3584 ········/// <param name="encodedShortId"></param>
3585 ········/// <returns></returns>
3586 ········public IPersistenceCapable FindObject(string encodedShortId)
3587 ········{
3588 ············string shortId = encodedShortId.Decode();
3589 ············string[] arr = shortId.Split( '-' );
3590 ············if (arr.Length != 3)
3591 ················throw new ArgumentException( "The format of the string is not valid", "shortId" );
3592 ············Type t = shortId.GetObjectType(this);··// try readable format
3593 ············if (t == null)
3594 ············{
3595 ················int typeCode = 0;
3596 ················if (!int.TryParse( arr[2], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out typeCode ))
3597 ····················throw new ArgumentException( "The string doesn't represent a loadable type", "shortId" );
3598 ················t = this.typeManager[typeCode];
3599 ················if (t == null)
3600 ····················throw new ArgumentException( "The string doesn't represent a loadable type", "shortId" );
3601 ············}
3602
3603 ············Class cls = GetClass( t );
3604 ············if (cls == null)
3605 ················throw new ArgumentException( "The type identified by the string is not persistent or is not managed by the given mapping file", "shortId" );
3606
3607 ············object[] keydata = new object[cls.Oid.OidColumns.Count];
3608 ············string[] oidValues = arr[2].Split( ' ' );
3609
3610 ············int i = 0;
3611 ············foreach (var oidValue in oidValues)
3612 ············{
3613 ················Type oidType = cls.Oid.OidColumns[i].SystemType;
3614 ················if (oidType == typeof( int ))
3615 ················{
3616 ····················int key;
3617 ····················if (!int.TryParse( oidValue, out key ))
3618 ························throw new ArgumentException( $"The ShortId value at index {i} doesn't contain an int value", nameof(encodedShortId) );
3619 ····················if (key > (int.MaxValue >> 1))
3620 ························key = -(int.MaxValue - key);
3621 ····················keydata[i] = key;
3622 ················}
3623 ················else if (oidType == typeof( Guid ))
3624 ················{
3625 ····················Guid key;
3626 ····················if (!Guid.TryParse( oidValue, out key ))
3627 ························throw new ArgumentException( $"The ShortId value at index {i} doesn't contain an Guid value", nameof( encodedShortId ) );
3628 ····················keydata[i] = key;
3629 ················}
3630 ················else if (oidType == typeof( string ))
3631 ················{
3632 ····················keydata[i] = oidValue;
3633 ················}
3634 ················else
3635 ················{
3636 ····················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 ) );
3637 ················}
3638
3639 ················i++;
3640 ············}
3641
3642 ············if (keydata.Length == 1)
3643 ················return FindObject( t, keydata[0] );
3644
3645 ············return FindObject( t, keydata );············
3646 ········}
3647
3648 ········/// <summary>
3649 ········/// Gets the requested object. If it is in the cache, the cached object is returned, otherwise, a new (hollow)
3650 ········/// instance of the object is returned. In either case, the DB is not accessed!
3651 ········/// </summary>
3652 ········/// <param name="id">Object id</param>
3653 ········/// <returns>The object to retrieve in hollow state</returns>········
3654 ········public IPersistenceCapable FindObject(ObjectId id)
3655 ········{
3656 ············if(id == null)
3657 ············{
3658 ················throw new ArgumentNullException("id");
3659 ············}
3660
3661 ············if(!id.IsValid())
3662 ············{
3663 ················throw new NDOException(86, "FindObject: Invalid object id. Object does not exist");
3664 ············}
3665
3666 ············IPersistenceCapable pc = cache.GetObject(id);
3667 ············if(pc == null)
3668 ············{
3669 ················pc = CreateObject(id.Id.Type);
3670 ················pc.NDOObjectId = id;
3671 ················pc.NDOStateManager = sm;
3672 ················pc.NDOObjectState = NDOObjectState.Hollow;
3673 ················cache.UpdateCache(pc);
3674 ············}
3675 ············return pc;
3676 ········}
3677
3678
3679 ········/// <summary>
3680 ········/// Reload an object from the database.
3681 ········/// </summary>
3682 ········/// <param name="o">The object to be reloaded.</param>
3683 ········public void Refresh(object o)
3684 ········{
3685 ············RefreshAsync( o ).ConfigureAwait( false ).GetAwaiter().GetResult();
3686 ········}
3687
3688 ········/// <summary>
3689 ········/// Reload an object from the database asynchronously.
3690 ········/// </summary>
3691 ········/// <param name="o">The object to be reloaded.</param>
3692 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3693 ········public virtual async Task RefreshAsync( object o, CancellationToken cancellationToken = default )
3694 ········{
3695 ············using (EnterOperation())
3696 ············{
3697 ················await RefreshInternalAsync( o, cancellationToken ).ConfigureAwait( false );
3698 ············}
3699 ········}
3700
3701 ········async Task RefreshInternalAsync( object o, CancellationToken cancellationToken )
3702 ········{
3703 ············IPersistenceCapable pc = CheckPc(o);
3704 ············if(pc.NDOObjectState == NDOObjectState.Transient || pc.NDOObjectState == NDOObjectState.Deleted)
3705 ············{
3706 ················throw new NDOException(87, "Refresh: Illegal state " + pc.NDOObjectState + " for this operation");
3707 ············}
3708
3709 ············if(pc.NDOObjectState == NDOObjectState.Created || pc.NDOObjectState == NDOObjectState.PersistentDirty)
3710 ················return; // Cannot update objects in current transaction
3711
3712 ············MakeHollow(pc);
3713 ············await LoadDataAsync( pc, cancellationToken ).ConfigureAwait( false );
3714 ········}
3715
3716 ········/// <summary>
3717 ········/// Refresh a list of objects.
3718 ········/// </summary>
3719 ········/// <param name="list">The list of objects to be refreshed.</param>
3720 ········public void Refresh(IList list)
3721 ········{
3722 ············RefreshAsync( list ).ConfigureAwait( false ).GetAwaiter().GetResult();
3723 ········}
3724
3725 ········/// <summary>
3726 ········/// Refresh a list of objects asynchronously.
3727 ········/// </summary>
3728 ········/// <param name="list">The list of objects to be refreshed.</param>
3729 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3730 ········/// <remarks>The objects are refreshed sequentially.</remarks>
3731 ········public virtual async Task RefreshAsync( IList list, CancellationToken cancellationToken = default )
3732 ········{
3733 ············using (EnterOperation())
3734 ············{
3735 ················foreach (IPersistenceCapable pc in list)
3736 ····················await RefreshAsync( (object) pc, cancellationToken ).ConfigureAwait( false );
3737 ············}
3738 ········}
3739
3740 ········/// <summary>
3741 ········/// Refreshes all unlocked objects in the cache.
3742 ········/// </summary>
3743 ········public void RefreshAll()
3744 ········{
3745 ············RefreshAllAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
3746 ········}
3747
3748 ········/// <summary>
3749 ········/// Refreshes all unlocked objects in the cache asynchronously.
3750 ········/// </summary>
3751 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3752 ········public virtual Task RefreshAllAsync( CancellationToken cancellationToken = default )
3753 ········{
3754 ············return RefreshAsync( cache.UnlockedObjects.ToList(), cancellationToken );
3755 ········}
3756
3757 ········/// <summary>
3758 ········/// Closes the PersistenceManager and releases all resources.
3759 ········/// </summary>
3760 ········public override async Task CloseAsync()
3761 ········{
3762 ············if (this.isClosing)
3763 ················return;
3764 ············this.isClosing = true;
3765 ············await TransactionScope.DisposeAsync().ConfigureAwait( false );
3766 ············UnloadCache();
3767 ············await base.CloseAsync().ConfigureAwait( false );
3768 ········}
3769
3770 ········internal void LogIfVerbose( string msg )
3771 ········{
3772 ············if (Logger != null && Logger.IsEnabled( LogLevel.Debug ))
3773 ················Logger.LogDebug( msg );
3774 ········}
3775
3776
3777 ········#endregion
3778
3779
3780
3781 #region Query engine
3782
3783
3784 ········/// <summary>
3785 ········/// Returns a virtual table for Linq queries.
3786 ········/// </summary>
3787 ········/// <typeparam name="T"></typeparam>
3788 ········/// <returns></returns>
3789 ········public VirtualTable<T> Objects<T>() //where T: IPersistenceCapable
3790 ········{
3791 ············return new VirtualTable<T>( this );
3792 ········}
3793
3794 ········
3795 ········/// <summary>
3796 ········/// Suppose, you had a directed 1:n relation from class A to class B. If you load an object of type B,
3797 ········/// 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
3798 ········/// a relation to A the foreign key would get lost if we discard the row after building the B object. To
3799 ········/// not lose the foreign key it will be stored as part of the object.
3800 ········/// </summary>
3801 ········/// <param name="cl"></param>
3802 ········/// <param name="pc"></param>
3803 ········/// <param name="row"></param>
3804 ········void ReadLostForeignKeysFromRow(Class cl, IPersistenceCapable pc, DataRow row)
3805 ········{
3806 ············if (cl.FKColumnNames != null && pc.NDOLoadState != null)
3807 ············{
3808 ················//················Debug.WriteLine("GetLostForeignKeysFromRow " + pc.NDOObjectId.Dump());
3809 ················KeyValueList kvl = new KeyValueList(cl.FKColumnNames.Count());
3810 ················foreach(string colName in cl.FKColumnNames)
3811 ····················kvl.Add(new KeyValuePair(colName, row[colName]));
3812 ················pc.NDOLoadState.LostRowInfo = kvl;················
3813 ············}
3814 ········}
3815
3816 ········/// <summary>
3817 ········/// Writes information into the data row, which cannot be stored in the object.
3818 ········/// </summary>
3819 ········/// <param name="cl"></param>
3820 ········/// <param name="pc"></param>
3821 ········/// <param name="row"></param>
3822 ········protected virtual void WriteLostForeignKeysToRow(Class cl, IPersistenceCapable pc, DataRow row)
3823 ········{
3824 ············if (cl.FKColumnNames != null)
3825 ············{
3826 ················//················Debug.WriteLine("WriteLostForeignKeys " + pc.NDOObjectId.Dump());
3827 ················KeyValueList kvl = (KeyValueList)pc.NDOLoadState.LostRowInfo;
3828 ················if (kvl == null)
3829 ····················throw new NDOException(88, "Can't find foreign keys for the relations of the object " + pc.NDOObjectId.Dump());
3830 ················foreach (KeyValuePair pair in kvl)
3831 ····················row[(string) pair.Key] = pair.Value;
3832 ············}
3833 ········}
3834
3835 ········void Row2Object(Class cl, IPersistenceCapable pc, DataRow row)
3836 ········{
3837 ············ReadObject(pc, row, cl.ColumnNames, 0);
3838 ············ReadTimeStamp(cl, pc, row);
3839 ············ReadLostForeignKeysFromRow(cl, pc, row);
3840 ············LoadRelated1To1Objects(pc, row);
3841 ············pc.NDOObjectState = NDOObjectState.Persistent;
3842 ········}
3843
3844
3845 ········/// <summary>
3846 ········/// Convert a data table to objects. Note that the table might only hold objects of the specified type.
3847 ········/// </summary>
3848 ········internal IList DataTableToIList(Type t, ICollection rows, bool hollow)
3849 ········{
3850 ············IList queryResult = GenericListReflector.CreateList(t, rows.Count);
3851 ············if (rows.Count == 0)
3852 ················return queryResult;
3853
3854 ············IList callbackObjects = new ArrayList();
3855 ············Class cl = GetClass(t);
3856 ············if (t.IsGenericTypeDefinition)
3857 ············{
3858 ················if (cl.TypeNameColumn == null)
3859 ····················throw new NDOException(104, "No type name column defined for generic type '" + t.FullName + "'. Check your mapping file.");
3860 ················IEnumerator en = rows.GetEnumerator();
3861 ················en.MoveNext();··// Move to the first element
3862 ················DataRow testrow = (DataRow)en.Current;
3863 ················if (testrow.Table.Columns[cl.TypeNameColumn.Name] == null)
3864 ····················throw new InternalException(3333, "DataTableToIList: TypeNameColumn isn't defined in the schema.");
3865 ············}
3866
3867 ············foreach(DataRow row in rows)
3868 ············{
3869 ················Type concreteType = t;
3870 ················if (t.IsGenericTypeDefinition)··// type information is in the row
3871 ················{
3872 ····················if (row[cl.TypeNameColumn.Name] == DBNull.Value)
3873 ····················{
3874 ························ObjectId tempid = ObjectIdFactory.NewObjectId(t, cl, row, this.typeManager);
3875 ························throw new NDOException(105, "Null entry in the TypeNameColumn of the type '" + t.FullName + "'. Oid = " + tempid.ToString());
3876 ····················}
3877 ····················string typeStr = (string)row[cl.TypeNameColumn.Name];
3878 ····················concreteType = Type.GetType(typeStr);
3879 ····················if (concreteType == null)
3880 ························throw new NDOException(106, "Can't load generic type " + typeStr);
3881 ················}
3882 ················ObjectId id = ObjectIdFactory.NewObjectId(concreteType, cl, row, this.typeManager);
3883 ················IPersistenceCapable pc = cache.GetObject(id);················
3884 ················if(pc == null)
3885 ················{
3886 ····················pc = CreateObject( concreteType );
3887 ····················pc.NDOObjectId = id;
3888 ····················pc.NDOStateManager = sm;
3889 ····················// If the object shouldn't be hollow, this will be overwritten later.
3890 ····················pc.NDOObjectState = NDOObjectState.Hollow;
3891 ················}
3892 ················// If we have found a non hollow object, the time stamp remains the old one.
3893 ················// In every other case we use the new time stamp.
3894 ················// Note, that there could be a hollow object in the cache.
3895 ················// We need the time stamp in hollow objects in order to correctly
3896 ················// delete objects using fake rows.
3897 ················if (pc.NDOObjectState == NDOObjectState.Hollow)
3898 ················{
3899 ····················ReadTimeStamp(cl, pc, row);
3900 ················}
3901 ················if(!hollow && pc.NDOObjectState != NDOObjectState.PersistentDirty)
3902 ················{
3903 ····················Row2Object(cl, pc, row);
3904 ····················if ((pc as IPersistenceNotifiable) != null)
3905 ························callbackObjects.Add(pc);
3906 ················}
3907
3908 ················cache.UpdateCache(pc);
3909 ················queryResult.Add(pc);
3910 ············}
3911 ············// Make shure this is the last statement before returning
3912 ············// to the caller, so the user can recursively use persistent
3913 ············// objects
3914 ············foreach(IPersistenceNotifiable ipn in callbackObjects)
3915 ················ipn.OnLoaded();
3916
3917 ············return queryResult;
3918 ········}
3919
3920 #endregion
3921
3922 #region Cache Management
3923 ········/// <summary>
3924 ········/// Remove all unused entries from the cache.
3925 ········/// </summary>
3926 ········public void CleanupCache()
3927 ········{
3928 ············GC.Collect(GC.MaxGeneration);
3929 ············GC.WaitForPendingFinalizers();
3930 ············cache.Cleanup();
3931 ········}
3932
3933 ········/// <summary>
3934 ········/// Remove all unlocked objects from the cache. Use with care!
3935 ········/// </summary>
3936 ········public void UnloadCache()
3937 ········{
3938 ············cache.Unload();
3939 ········}
3940 #endregion
3941
3942 ········/// <summary>
3943 ········/// Default encryption key for NDO
3944 ········/// </summary>
3945 ········/// <remarks>
3946 ········/// We recommend strongly to use an own encryption key, which can be set with this property.
3947 ········/// </remarks>
3948 ········public virtual byte[] EncryptionKey
3949 ········{
3950 ············get
3951 ············{
3952 ················if (this.encryptionKey == null)
3953 ····················this.encryptionKey = new byte[] { 0x09,0xA2,0x79,0x5C,0x99,0xFF,0xCB,0x8B,0xA3,0x37,0x76,0xC8,0xA6,0x5D,0x6D,0x66,
3954 ······················································0xE2,0x74,0xCF,0xF0,0xF7,0xEA,0xC4,0x82,0x1E,0xD5,0x19,0x4C,0x5A,0xB4,0x89,0x4D };
3955 ················return this.encryptionKey;
3956 ············}
3957 ············set { this.encryptionKey = value; }
3958 ········}
3959
3960 ········/// <summary>
3961 ········/// Hollow mode: If true all objects are made hollow after each transaction.
3962 ········/// </summary>
3963 ········public virtual bool HollowMode
3964 ········{
3965 ············get { return hollowMode; }
3966 ············set { hollowMode = value; }
3967 ········}
3968
3969 ········internal TypeManager TypeManager
3970 ········{
3971 ············get { return typeManager; }
3972 ········}
3973
3974 ········/// <summary>
3975 ········/// Sets or gets transaction mode. Uses TransactionMode enum.
3976 ········/// </summary>
3977 ········/// <remarks>
3978 ········/// Set this value before you start any transactions.
3979 ········/// </remarks>
3980 ········public TransactionMode TransactionMode
3981 ········{
3982 ············get { return TransactionScope.TransactionMode; }
3983 ············set { TransactionScope.TransactionMode = value; }
3984 ········}
3985
3986 ········/// <summary>
3987 ········/// Sets or gets the Isolation Level.
3988 ········/// </summary>
3989 ········/// <remarks>
3990 ········/// Set this value before you start any transactions.
3991 ········/// </remarks>
3992 ········public IsolationLevel IsolationLevel
3993 ········{
3994 ············get { return TransactionScope.IsolationLevel; }
3995 ············set { TransactionScope.IsolationLevel = value; }
3996 ········}
3997
3998 ········internal class MappingTableEntry
3999 ········{
4000 ············private IPersistenceCapable parentObject;
4001 ············private IPersistenceCapable relatedObject;
4002 ············private Relation relation;
4003 ············private bool deleteEntry;
4004 ············
4005 ············public MappingTableEntry(IPersistenceCapable pc, IPersistenceCapable relObj, Relation r) : this(pc, relObj, r, false)
4006 ············{
4007 ············}
4008 ············
4009 ············public MappingTableEntry(IPersistenceCapable pc, IPersistenceCapable relObj, Relation r, bool deleteEntry)
4010 ············{
4011 ················parentObject = pc;
4012 ················relatedObject = relObj;
4013 ················relation = r;
4014 ················this.deleteEntry = deleteEntry;
4015 ············}
4016
4017 ············public bool DeleteEntry
4018 ············{
4019 ················get
4020 ················{
4021 ····················return deleteEntry;
4022 ················}
4023 ············}
4024
4025 ············public IPersistenceCapable ParentObject
4026 ············{
4027 ················get
4028 ················{
4029 ····················return parentObject;
4030 ················}
4031 ············}
4032
4033 ············public IPersistenceCapable RelatedObject
4034 ············{
4035 ················get
4036 ················{
4037 ····················return relatedObject;
4038 ················}
4039 ············}
4040
4041 ············public Relation Relation
4042 ············{
4043 ················get
4044 ················{
4045 ····················return relation;
4046 ················}
4047 ············}
4048 ········}
4049
4050 ········/// <summary>
4051 ········/// Get a DataRow representing the given object.
4052 ········/// </summary>
4053 ········/// <param name="o"></param>
4054 ········/// <returns></returns>
4055 ········public DataRow GetClonedDataRow( object o )
4056 ········{
4057 ············IPersistenceCapable pc = CheckPc( o );
4058
4059 ············if (pc.NDOObjectState == NDOObjectState.Deleted || pc.NDOObjectState == NDOObjectState.Transient)
4060 ················throw new Exception( "GetDataRow: State of the object must not be Deleted or Transient." );
4061
4062 ············DataRow row = cache.GetDataRow( pc );
4063 ············DataTable newTable = row.Table.Clone();
4064 ············newTable.ImportRow( row );
4065 ············row = newTable.Rows[0];
4066
4067 ············Class cls = mappings.FindClass(o.GetType());
4068 ············WriteObject( pc, row, cls.ColumnNames );
4069 ············WriteForeignKeysToRow( pc, row );
4070
4071 ············return row;
4072 ········}
4073
4074 ········/// <summary>
4075 ········/// Gets an object, which shows all changes applied to the given object.
4076 ········/// This function can be used to build an audit system.
4077 ········/// </summary>
4078 ········/// <param name="o"></param>
4079 ········/// <returns>An ExpandoObject</returns>
4080 ········public ChangeLog GetChangeSet( object o )
4081 ········{
4082 ············var changeLog = new ChangeLog(this);
4083 ············changeLog.Initialize( o );
4084 ············return changeLog;
4085 ········}
4086
4087 ········/// <summary>
4088 ········/// Outputs a revision number representing the assembly version.
4089 ········/// </summary>
4090 ········/// <remarks>This can be used for debugging purposes</remarks>
4091 ········public int Revision
4092 ········{
4093 ············get
4094 ············{
4095 ················Version v = new AssemblyName( GetType().Assembly.FullName ).Version;
4096 ················string vstring = String.Format( "{0}{1:D2}{2}{3:D2}", v.Major, v.Minor, v.Build, v.MinorRevision );
4097 ················return int.Parse( vstring );
4098 ············}
4099 ········}
4100 ····}
4101 }
4102
New Commit (c2b1662)
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 using System.Linq.Expressions;
49
50
51 namespace NDO
52 {
53 ····/// <summary>
54 ····/// Delegate type of an handler, which can be registered by the CollisionEvent of the PersistenceManager.
55 ····/// <see cref="NDO.PersistenceManager.CollisionEvent"/>
56 ····/// </summary>
57 ····public delegate void CollisionHandler(object o);
58 ····/// <summary>
59 ····/// Delegate type of an handler, which can be registered by the IdGenerationEvent event of the PersistenceManager.
60 ····/// <see cref="NDO.PersistenceManagerBase.IdGenerationEvent"/>
61 ····/// </summary>
62 ····public delegate void IdGenerationHandler(Type t, ObjectId oid);
63 ····/// <summary>
64 ····/// Delegate type of an handler, which can be registered by the OnSaving event of the PersistenceManager.
65 ····/// </summary>
66 ····public delegate void OnSavingHandler(ICollection l);
67 ····/// <summary>
68 ····/// Delegate type for the OnSavedEvent.
69 ····/// </summary>
70 ····/// <param name="auditSet"></param>
71 ····public delegate void OnSavedHandler(AuditSet auditSet);
72
73 ····/// <summary>
74 ····/// 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.
75 ····/// </summary>
76 ····/// <param name="pc"></param>
77 ····/// <returns>A boolean value which determines, if the handler could solve the situation.</returns>
78 ····/// <remarks>If the handler returns false, NDO will throw an exception.</remarks>
79 ····public delegate bool ObjectNotPresentHandler( IPersistenceCapable pc );
80
81 ····/// <summary>
82 ····/// Standard implementation of the IPersistenceManager interface. Provides transaction like manipulation of data sets.
83 ····/// 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.
84 ····/// </summary>
85 ····public class PersistenceManager : PersistenceManagerBase, IPersistenceManager
86 ····{········
87 ········private bool hollowMode = false;
88 ········private Dictionary<Relation, IMappingTableHandler> mappingHandler = new Dictionary<Relation,IMappingTableHandler>(); // currently used handlers
89
90 ········private Hashtable currentRelations = new Hashtable(); // Contains names of current bidirectional relations
91 ········private ObjectLock removeLock = new ObjectLock();
92 ········private ObjectLock addLock = new ObjectLock();
93 ········private ArrayList createdDirectObjects = new ArrayList(); // List of newly created objects that need to be stored twice to update foreign keys.
94 ········// List of created objects that use mapping table and need to be stored in mapping table
95 ········// after they have been stored to the database to update foreign keys.
96 ········private ArrayList createdMappingTableObjects = new ArrayList();··
97 ········private TypeManager typeManager;
98 ········internal bool DeferredMode { get; private set; }
99 ········private INDOTransactionScope transactionScope;
100 ········internal INDOTransactionScope TransactionScope => transactionScope ?? (transactionScope = ServiceProvider.GetRequiredService<INDOTransactionScope>().Initialize(this));········
101
102 ········private OpenConnectionListener openConnectionListener;
103
104 ········/// <summary>
105 ········/// Register a listener to this event if you work in concurrent scenarios and you use TimeStamps.
106 ········/// If a collision occurs, this event gets fired and gives the opportunity to handle the situation.
107 ········/// </summary>
108 ········public event CollisionHandler CollisionEvent;
109
110 ········/// <summary>
111 ········/// Register a listener to this event to handle situations where LoadData doesn't find an object.
112 ········/// The listener can determine, whether an exception should be thrown, if the situation occurs.
113 ········/// </summary>
114 ········public event ObjectNotPresentHandler ObjectNotPresentEvent;
115
116 ········/// <summary>
117 ········/// Register a listener to this event, if you want to be notified about the end
118 ········/// of a transaction. The listener gets a ICollection of all objects, which have been changed
119 ········/// during the transaction and are to be saved or deleted.
120 ········/// </summary>
121 ········public event OnSavingHandler OnSavingEvent;
122 ········/// <summary>
123 ········/// This event is fired at the very end of the Save() method. It provides lists of the added, changed, and deleted objects.
124 ········/// </summary>
125 ········public event OnSavedHandler OnSavedEvent;
126 ········
127 ········private const string hollowMarker = "Hollow";
128 ········private byte[] encryptionKey;
129 ········private List<RelationChangeRecord> relationChanges = new List<RelationChangeRecord>();
130 ········private bool isClosing = false;
131
132 ········/// <summary>
133 ········/// Gets a list of structures which represent relation changes, i.e. additions and removals
134 ········/// </summary>
135 ········protected internal List<RelationChangeRecord> RelationChanges
136 ········{
137 ············get { return this.relationChanges; }
138 ········}
139
140 ········/// <summary>
141 ········/// Initializes a new PersistenceManager instance.
142 ········/// </summary>
143 ········/// <param name="mappingFileName"></param>
144 ········protected override void Init(string mappingFileName)
145 ········{
146 ············try
147 ············{
148 ················base.Init(mappingFileName);
149 ············}
150 ············catch (Exception ex)
151 ············{
152 ················if (ex is NDOException)
153 ····················throw;
154 ················throw new NDOException(30, "Persistence manager initialization error: " + ex.ToString(), ex);
155 ············}
156
157 ········}
158
159 ········/// <summary>
160 ········/// Initializes the persistence manager
161 ········/// </summary>
162 ········/// <remarks>
163 ········/// Note: This is the method, which will be called from all different ways to instantiate a PersistenceManagerBase.
164 ········/// </remarks>
165 ········/// <param name="mapping"></param>
166 ········internal override void Init( Mappings mapping )
167 ········{
168 ············base.Init( mapping );
169
170 ············string dir = Path.GetDirectoryName( mapping.FileName );
171
172 ············string typesFile = Path.Combine( dir, "NDOTypes.xml" );
173 ············typeManager = new TypeManager( typesFile, this.mappings );
174
175 ············sm = new StateManager( this );
176
177 ············InitClasses();
178 ········}
179
180
181 ········/// <summary>
182 ········/// Standard Constructor.
183 ········/// </summary>
184 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
185 ········/// <remarks>
186 ········/// Searches for a mapping file in the application directory.
187 ········/// The constructor tries to find a file with the same name as
188 ········/// the assembly, but with the extension .ndo.xml. If the file is not found the constructor tries to find a
189 ········/// file called AssemblyName.ndo.mapping in the application directory.
190 ········/// </remarks>
191 ········public PersistenceManager( IServiceProvider scopedServiceProvider = null ) : base( scopedServiceProvider )
192 ········{
193 ········}
194
195 ········/// <summary>
196 ········/// Loads the mapping file from the specified location. This allows to use
197 ········/// different mapping files with different classes mapped in it.
198 ········/// </summary>
199 ········/// <param name="mappingFile">Path to the mapping file.</param>
200 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
201 ········/// <remarks>Only the Professional and Enterprise
202 ········/// Editions can handle more than one mapping file.</remarks>
203 ········public PersistenceManager(string mappingFile, IServiceProvider scopedServiceProvider = null) : base (mappingFile, scopedServiceProvider)
204 ········{
205 ········}
206
207 ········/// <summary>
208 ········/// Constructs a PersistenceManager and reuses a cached NDOMapping.
209 ········/// </summary>
210 ········/// <param name="mapping">The cached mapping object</param>
211 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
212 ········public PersistenceManager(NDOMapping mapping, IServiceProvider scopedServiceProvider = null) : base (mapping, scopedServiceProvider)
213 ········{
214 ········}
215
216 ········#region Object Container Stuff
217 ········/// <summary>
218 ········/// Gets a container of all loaded objects and tries to load all child objects,
219 ········/// which are reachable through composite relations.
220 ········/// </summary>
221 ········/// <returns>An ObjectContainer object.</returns>
222 ········/// <remarks>
223 ········/// It is not recommended, to transfer objects with a state other than Hollow,
224 ········/// Persistent, or Transient.
225 ········/// The transfer format is binary.
226 ········/// </remarks>
227 ········public ObjectContainer GetObjectContainer()
228 ········{
229 ············IList l = this.cache.AllObjects;
230 ············foreach(IPersistenceCapable pc in l)
231 ············{
232 ················if (pc.NDOObjectState == NDOObjectState.PersistentDirty)
233 ················{
234 ····················if (Logger != null)
235 ························Logger.LogWarning( "Call to GetObjectContainer returns changed objects." );
236 ················}
237 ············}
238
239 ············ObjectContainer oc = new ObjectContainer();
240 ············oc.AddList(l);
241 ············return oc;
242 ········}
243
244 ········/// <summary>
245 ········/// Returns a container of all objects provided in the objects list and searches for
246 ········/// child objects according to the serFlags.
247 ········/// </summary>
248 ········/// <param name="objects">The list of the root objects to add to the container.</param>
249 ········/// <returns>An ObjectContainer object.</returns>
250 ········/// <remarks>
251 ········/// It is not recommended, to transfer objects with a state other than Hollow,
252 ········/// Persistent, or Transient.
253 ········/// </remarks>
254 ········public ObjectContainer GetObjectContainer(IList objects)
255 ········{
256 ············foreach(object o in objects)
257 ············{
258 ················CheckPc(o);
259 ················IPersistenceCapable pc = o as IPersistenceCapable;
260 ················if (pc.NDOObjectState == NDOObjectState.Hollow)
261 ····················LoadData(pc);
262 ············}
263 ············ObjectContainer oc = new ObjectContainer();
264 ············oc.AddList(objects);
265 ············return oc;
266 ········}
267
268
269 ········/// <summary>
270 ········/// Returns a container containing the provided object
271 ········/// and tries to load all child objects
272 ········/// reachable through composite relations.
273 ········/// </summary>
274 ········/// <param name="obj">The object to be added to the container.</param>
275 ········/// <returns>An ObjectContainer object.</returns>
276 ········/// <remarks>
277 ········/// It is not recommended, to transfer objects with a state other than Hollow,
278 ········/// Persistent, or Transient.
279 ········/// The transfer format is binary.
280 ········/// </remarks>
281 ········public ObjectContainer GetObjectContainer(Object obj)
282 ········{
283 ············CheckPc(obj);
284 ············if (((IPersistenceCapable)obj).NDOObjectState == NDOObjectState.Hollow)
285 ················LoadData(obj);
286 ············ObjectContainer oc = new ObjectContainer();
287 ············oc.AddObject(obj);
288 ············return oc;
289 ········}
290
291 ········/// <summary>
292 ········/// Merges an object container to the active objects in the pm. All changes and the state
293 ········/// of the objects will be taken over by the pm.
294 ········/// </summary>
295 ········/// <remarks>
296 ········/// The parameter can be either an ObjectContainer or a ChangeSetContainer.
297 ········/// The flag MarkAsTransient can be used to perform a kind
298 ········/// of object based replication using the ObjectContainer class.
299 ········/// Objects, which are persistent at one machine, can be transfered
300 ········/// to a second machine and treated by the receiving PersistenceManager like a newly created
301 ········/// object. The receiving PersistenceManager will use MakePersistent to store the whole
302 ········/// transient object tree.
303 ········/// There is one difference to freshly created objects: If an object id exists, it will be
304 ········/// serialized. If the NDOOidType-Attribute is valid for the given class, the transfered
305 ········/// oids will be reused by the receiving PersistenceManager.
306 ········/// </remarks>
307 ········/// <param name="ocb">The object container to be merged.</param>
308 ········public void MergeObjectContainer(ObjectContainerBase ocb)
309 ········{
310 ············ChangeSetContainer csc = ocb as ChangeSetContainer;
311 ············if (csc != null)
312 ············{
313 ················MergeChangeSet(csc);
314 ················return;
315 ············}
316 ············ObjectContainer oc = ocb as ObjectContainer;
317 ············if (oc != null)
318 ············{
319 ················InternalMergeObjectContainer(oc);
320 ················return;
321 ············}
322 ············throw new NDOException(42, "Wrong argument type: MergeObjectContainer expects either an ObjectContainer or a ChangeSetContainer object as parameter.");
323 ········}
324
325
326 ········void InternalMergeObjectContainer(ObjectContainer oc)
327 ········{
328 ············// TODO: Check, if other states are useful. Find use scenarios.
329 ············foreach(IPersistenceCapable pc in oc.RootObjects)
330 ············{
331 ················if (pc.NDOObjectState == NDOObjectState.Transient)
332 ····················MakePersistent(pc);
333 ············}
334 ············foreach(IPersistenceCapable pc in oc.RootObjects)
335 ············{
336 ················new OnlineMergeIterator(this.sm, this.cache).Iterate(pc);
337 ············}
338 ········}
339
340 ········void MergeChangeSet(ChangeSetContainer cs)
341 ········{
342 ············foreach(IPersistenceCapable pc in cs.AddedObjects)
343 ············{
344 ················InternalMakePersistent(pc, false);
345 ············}
346 ············foreach(ObjectId oid in cs.DeletedObjects)
347 ············{
348 ················IPersistenceCapable pc2 = FindObject(oid);
349 ················Delete(pc2);
350 ············}
351 ············foreach(IPersistenceCapable pc in cs.ChangedObjects)
352 ············{
353 ················IPersistenceCapable pc2 = FindObject(pc.NDOObjectId);
354 ················Class pcClass = GetClass(pc);
355 ················// Make sure, the object is loaded.
356 ················if (pc2.NDOObjectState == NDOObjectState.Hollow)
357 ····················LoadData(pc2);
358 ················MarkDirty( pc2 );··// This locks the object and generates a LockEntry, which contains a row
359 ················var entry = cache.LockedObjects.FirstOrDefault( e => e.pc.NDOObjectId == pc.NDOObjectId );
360 ················DataRow row = entry.row;
361 ················pc.NDOWrite(row, pcClass.ColumnNames, 0);
362 ················pc2.NDORead(row, pcClass.ColumnNames, 0);
363 ············}
364 ············foreach(RelationChangeRecord rcr in cs.RelationChanges)
365 ············{
366 ················IPersistenceCapable parent = FindObject(rcr.Parent.NDOObjectId);
367 ················IPersistenceCapable child = FindObject(rcr.Child.NDOObjectId);
368 ················Class pcClass = GetClass(parent);
369 ················Relation r = pcClass.FindRelation(rcr.RelationName);
370 ················if (!parent.NDOLoadState.RelationLoadState[r.Ordinal])
371 ····················LoadRelation(parent, r, true);
372 ················if (rcr.IsAdded)
373 ················{
374 ····················InternalAddRelatedObject(parent, r, child, true);
375 ····················if (r.Multiplicity == RelationMultiplicity.Element)
376 ····················{
377 ························mappings.SetRelationField(parent, r.FieldName, child);
378 ····················}
379 ····················else
380 ····················{
381 ························IList l = mappings.GetRelationContainer(parent, r);
382 ························l.Add(child);
383 ····················}
384 ················}
385 ················else
386 ················{
387 ····················RemoveRelatedObject(parent, r.FieldName, child);
388 ····················if (r.Multiplicity == RelationMultiplicity.Element)
389 ····················{
390 ························mappings.SetRelationField(parent, r.FieldName, null);
391 ····················}
392 ····················else
393 ····················{
394 ························IList l = mappings.GetRelationContainer(parent, r);
395 ························try
396 ························{
397 ····························ObjectListManipulator.Remove(l, child);
398 ························}
399 ························catch
400 ························{
401 ····························throw new NDOException(50, "Error while merging a ChangeSetContainer: Child " + child.NDOObjectId.ToString() + " doesn't exist in relation " + parent.GetType().FullName + '.' + r.FieldName);
402 ························}
403 ····················}
404 ················}
405 ············}
406
407 ········}
408 ········#endregion
409
410 ········#region Implementation of IPersistenceManager
411
412 ········// Complete documentation can be found in IPersistenceManager
413
414
415 ········void WriteDependentForeignKeysToRow(IPersistenceCapable pc, Class cl, DataRow row)
416 ········{
417 ············if (!cl.Oid.IsDependent)
418 ················return;
419 ············WriteForeignKeysToRow(pc, row);
420 ········}
421
422 ········void InternalMakePersistent(IPersistenceCapable pc, bool checkRelations)
423 ········{
424 ············// Object is now under control of the state manager
425 ············pc.NDOStateManager = sm;
426
427 ············Type pcType = pc.GetType();
428 ············Class pcClass = GetClass(pc);
429
430 ············// Create new object
431 ············DataTable dt = GetTable(pcType);
432 ············DataRow row = dt.NewRow();·· // In case of autoincremented oid, the row has a temporary oid value
433
434 ············// In case of a Guid oid the value will be computed now.
435 ············foreach (OidColumn oidColumn in pcClass.Oid.OidColumns)
436 ············{
437 ················if (oidColumn.SystemType == typeof(Guid) && oidColumn.FieldName == null && oidColumn.RelationName ==null)
438 ················{
439 ····················if (dt.Columns[oidColumn.Name].DataType == typeof(string))
440 ························row[oidColumn.Name] = Guid.NewGuid().ToString();
441 ····················else
442 ························row[oidColumn.Name] = Guid.NewGuid();
443 ················}
444 ············}
445
446 ············WriteObject(pc, row, pcClass.ColumnNames, 0); // save current state in DS
447
448 ············// If the object is merged from an ObjectContainer, the id should be reused,
449 ············// if the id is client generated (not Autoincremented).
450 ············// In every other case, the oid is set to null, to force generating a new oid.
451 ············bool fireIdGeneration = (Object)pc.NDOObjectId == null;
452 ············if ((object)pc.NDOObjectId != null)
453 ············{
454 ················bool hasAutoincrement = false;
455 ················foreach (OidColumn oidColumn in pcClass.Oid.OidColumns)
456 ················{
457 ····················if (oidColumn.AutoIncremented)
458 ····················{
459 ························hasAutoincrement = true;
460 ························break;
461 ····················}
462 ················}
463 ················if (hasAutoincrement) // can't store existing id
464 ················{
465 ····················pc.NDOObjectId = null;
466 ····················fireIdGeneration = true;
467 ················}
468 ············}
469
470 ············// In case of a dependent class the oid has to be read from the fields according to the relations
471 ············WriteDependentForeignKeysToRow(pc, pcClass, row);
472
473 ············if ((object)pc.NDOObjectId == null)
474 ············{
475 ················pc.NDOObjectId = ObjectIdFactory.NewObjectId(pcType, pcClass, row, this.typeManager);
476 ············}
477
478 ············if (!pcClass.Oid.IsDependent) // Dependent keys can't be filled with user defined data
479 ············{
480 ················if (fireIdGeneration)
481 ····················FireIdGenerationEvent(pcType, pc.NDOObjectId);
482 ················// At this place the oid might have been
483 ················// - deserialized (MergeObjectContainer)
484 ················// - created using NewObjectId
485 ················// - defined by the IdGenerationEvent
486
487 ················// At this point we have a valid oid.
488 ················// If the object has a field mapped to the oid we have
489 ················// to write back the oid to the field
490 ················int i = 0;
491 ················new OidColumnIterator(pcClass).Iterate(delegate(OidColumn oidColumn, bool isLastElement)
492 ················{
493 ····················if (oidColumn.FieldName != null)
494 ····················{
495 ························FieldInfo fi = new BaseClassReflector(pcType).GetField(oidColumn.FieldName, BindingFlags.NonPublic | BindingFlags.Instance);
496 ························fi.SetValue(pc, pc.NDOObjectId.Id[i]);
497 ····················}
498 ····················i++;
499 ················});
500
501
502
503 ················// Now write back the data into the row
504 ················pc.NDOObjectId.Id.ToRow(pcClass, row);
505 ············}
506
507 ············
508 ············ReadLostForeignKeysFromRow(pcClass, pc, row);··// they contain all DBNull at the moment
509 ············dt.Rows.Add(row);
510
511 ············cache.Register(pc);
512
513 ············// new object that has never been written to the DS
514 ············pc.NDOObjectState = NDOObjectState.Created;
515 ············// Mark all Relations as loaded
516 ············SetRelationState(pc);
517
518 ············if (checkRelations)
519 ············{
520 ················// Handle related objects:
521 ················foreach(Relation r in pcClass.Relations)
522 ················{
523 ····················if (r.Multiplicity == RelationMultiplicity.Element)
524 ····················{
525 ························IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
526 ························if(child != null)
527 ························{
528 ····························AddRelatedObject(pc, r, child);
529 ························}
530 ····················}
531 ····················else
532 ····················{
533 ························IList list = mappings.GetRelationContainer(pc, r);
534 ························if(list != null)
535 ························{
536 ····························foreach(IPersistenceCapable relObj in list)
537 ····························{
538 ································if (relObj != null)
539 ····································AddRelatedObject(pc, r, relObj);
540 ····························}
541 ························}
542 ····················}
543 ················}
544 ············}
545
546 ············var relations··= CollectRelationStates(pc);
547 ············cache.Lock(pc, row, relations);
548 ········}
549
550
551 ········/// <summary>
552 ········/// Make an object persistent.
553 ········/// </summary>
554 ········/// <param name="o">the transient object that should be made persistent</param>
555 ········public void MakePersistent(object o)
556 ········{
557 ············if (IsClosed)
558 ················throw new ObjectDisposedException( GetType().Name );····
559
560 ············IPersistenceCapable pc = CheckPc(o);
561
562 ············//Debug.WriteLine("MakePersistent: " + pc.GetType().Name);
563 ············//Debug.Indent();
564
565 ············if (pc.NDOObjectState != NDOObjectState.Transient)
566 ················throw new NDOException(54, "MakePersistent: Object is already persistent: " + pc.NDOObjectId.Dump());
567
568 ············InternalMakePersistent(pc, true);
569
570 ········}
571
572
573
574 ········//········/// <summary>
575 ········//········/// Checks, if an object has a valid id, which was created by the database
576 ········//········/// </summary>
577 ········//········/// <param name="pc"></param>
578 ········//········/// <returns></returns>
579 ········//········private bool HasValidId(IPersistenceCapable pc)
580 ········//········{
581 ········//············if (this.IdGenerationEvent != null)
582 ········//················return true;
583 ········//············return (pc.NDOObjectState != NDOObjectState.Created && pc.NDOObjectState != NDOObjectState.Transient);
584 ········//········}
585
586
587 ········private void CreateAddedObjectRow(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj, bool makeRelObjPersistent)
588 ········{
589 ············// for a "1:n"-Relation w/o mapping table, we add the foreign key here.
590 ············if(r.HasSubclasses)
591 ············{
592 ················// we don't support 1:n with foreign fields in subclasses because we would have to
593 ················// search for objects in all subclasses! Instead use a mapping table.
594 ················// throw new NDOException(55, "1:n Relations with subclasses must use a mapping table: " + r.FieldName);
595 ················Debug.WriteLine("CreateAddedObjectRow: Polymorphic 1:n-relation " + r.Parent.FullName + "." + r.FieldName + " w/o mapping table");
596 ············}
597
598 ············if (!makeRelObjPersistent)
599 ················MarkDirty(relObj);
600 ············// Because we just marked the object as dirty, we know it's in the cache, so we don't supply the idColumn
601 ············DataRow relObjRow = this.cache.GetDataRow(relObj);
602
603 ············if (relObjRow == null)
604 ················throw new InternalException(537, "CreateAddedObjectRow: relObjRow == null");
605
606 ············pc.NDOObjectId.Id.ToForeignKey(r, relObjRow);
607
608 ············if (relObj.NDOLoadState.LostRowInfo == null)
609 ············{
610 ················ReadLostForeignKeysFromRow(GetClass(relObj), relObj, relObjRow);
611 ············}
612 ············else
613 ············{
614 ················relObj.NDOLoadState.ReplaceRowInfos(r, pc.NDOObjectId.Id);
615 ············}
616 ········}
617
618 ········private void PatchForeignRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
619 ········{
620 ············switch(relObj.NDOObjectState)
621 ············{
622 ················case NDOObjectState.Persistent:
623 ····················MarkDirty(relObj);
624 ····················break;
625 ················case NDOObjectState.Hollow:
626 ····················LoadData(relObj);
627 ····················MarkDirty(relObj);
628 ····················break;
629 ············}
630
631 ············if(r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
632 ············{
633 ················IPersistenceCapable newpc;
634 ················if((newpc = (IPersistenceCapable) mappings.GetRelationField(relObj, r.ForeignRelation.FieldName)) != null)
635 ················{
636 ····················if (newpc != pc)
637 ························throw new NDOException(56, "Object is already part of another relation: " + relObj.NDOObjectId.Dump());
638 ················}
639 ················else
640 ················{
641 ····················mappings.SetRelationField(relObj, r.ForeignRelation.FieldName, pc);
642 ················}
643 ············}
644 ············else
645 ············{
646 ················if (!relObj.NDOGetLoadState(r.ForeignRelation.Ordinal))
647 ····················LoadRelation(relObj, r.ForeignRelation, true);
648 ················IList l = mappings.GetRelationContainer(relObj, r.ForeignRelation);
649 ················if(l == null)
650 ················{
651 ····················try
652 ····················{
653 ························l = mappings.CreateRelationContainer(relObj, r.ForeignRelation);
654 ····················}
655 ····················catch
656 ····················{
657 ························throw new NDOException(57, "Can't construct IList member " + relObj.GetType().FullName + "." + r.FieldName + ". Initialize the field in the default class constructor.");
658 ····················}
659 ····················mappings.SetRelationContainer(relObj, r.ForeignRelation, l);
660 ················}
661 ················// Hack: Es sollte erst gar nicht zu diesem Aufruf kommen.
662 ················// Zus�tzlicher Funktions-Parameter addObjectToList oder so.
663 ················if (!ObjectListManipulator.Contains(l, pc))
664 ····················l.Add(pc);
665 ············}
666 ············//AddRelatedObject(relObj, r.ForeignRelation, pc);
667 ········}
668
669
670 ········/// <summary>
671 ········/// Add a related object to the specified object.
672 ········/// </summary>
673 ········/// <param name="pc">the parent object</param>
674 ········/// <param name="fieldName">the field name of the relation</param>
675 ········/// <param name="relObj">the related object that should be added</param>
676 ········internal virtual void AddRelatedObject(IPersistenceCapable pc, string fieldName, IPersistenceCapable relObj)
677 ········{
678 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient);
679 ············Relation r = mappings.FindRelation(pc, fieldName);
680 ············AddRelatedObject(pc, r, relObj);
681 ········}
682
683 ········/// <summary>
684 ········/// Core functionality to add an object to a relation container or relation field.
685 ········/// </summary>
686 ········/// <param name="pc"></param>
687 ········/// <param name="r"></param>
688 ········/// <param name="relObj"></param>
689 ········/// <param name="isMerging"></param>
690 ········protected virtual void InternalAddRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj, bool isMerging)
691 ········{
692 ············
693 ············// avoid recursion
694 ············if (!addLock.GetLock(relObj))
695 ················return;
696
697 ············try
698 ············{
699 ················if (r.MappingTable != null)
700 ····················CheckDuplicateMappingTableEntry(pc, r, relObj);
701
702 ················//TODO: We need a relation management, which is independent of
703 ················//the state management of an object. Currently the relation
704 ················//lists or elements are cached for restore, if an object is marked dirty.
705 ················//Thus we have to mark dirty our parent object in any case at the moment.
706 ················MarkDirty(pc);
707
708 ················//We should mark pc as dirty if we have a 1:1 w/o mapping table
709 ················//We should mark relObj as dirty if we have a 1:n w/o mapping table
710 ················//The latter happens in CreateAddedObjectRow
711
712 ················Class relClass = GetClass(relObj);
713
714 ················if (r.Multiplicity == RelationMultiplicity.Element
715 ····················&& r.HasSubclasses
716 ····················&& r.MappingTable == null················
717 ····················&& !this.HasOwnerCreatedIds
718 ····················&& GetClass(pc).Oid.HasAutoincrementedColumn
719 ····················&& !relClass.HasGuidOid)
720 ················{
721 ····················if (pc.NDOObjectState == NDOObjectState.Created && (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient ))
722 ························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.");
723 ····················if (r.Composition)
724 ························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.");
725 ····················if (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient)
726 ························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." );
727 ················}
728
729 ················bool isDependent = relClass.Oid.IsDependent;
730
731 ················if (r.Multiplicity == RelationMultiplicity.Element && isDependent)
732 ····················throw new NDOException(28, "Relations to intermediate classes must have RelationMultiplicity.List.");
733
734 ················// Need to patch pc into the relation relObj->pc, because
735 ················// the oid is built on base of this information
736 ················if (isDependent)
737 ················{
738 ····················CheckDependentKeyPreconditions(pc, r, relObj, relClass);
739 ················}
740
741 ················if (r.Composition || isDependent)
742 ················{
743 ····················if (!isMerging || relObj.NDOObjectState == NDOObjectState.Transient)
744 ························MakePersistent(relObj);
745 ················}
746
747 ················if(r.MappingTable == null)
748 ················{
749 ····················if (r.Bidirectional)
750 ····················{
751 ························// This object hasn't been saved yet, so the key is wrong.
752 ························// Therefore, the child must be written twice to update the foreign key.
753 #if trace
754 ························System.Text.StringBuilder sb = new System.Text.StringBuilder();
755 ························if (r.Multiplicity == RelationMultiplicity.Element)
756 ····························sb.Append("1");
757 ························else
758 ····························sb.Append("n");
759 ························sb.Append(":");
760 ························if (r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
761 ····························sb.Append("1");
762 ························else
763 ····························sb.Append("n");
764 ························sb.Append ("OwnCreatedOther");
765 ························sb.Append(relObj.NDOObjectState.ToString());
766 ························sb.Append(' ');
767
768 ························sb.Append(types[0].ToString());
769 ························sb.Append(' ');
770 ························sb.Append(types[1].ToString());
771 ························Debug.WriteLine(sb.ToString());
772 #endif
773 ························//························if (r.Multiplicity == RelationMultiplicity.Element
774 ························//····························&& r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
775 ························//························{
776 ························// Element means:
777 ························// pc is keyholder
778 ························// -> relObj is saved first
779 ························// -> UpdateOrder(pc) > UpdateOrder(relObj)
780 ························// Both are Created - use type sort order
781 ························if (pc.NDOObjectState == NDOObjectState.Created && (relObj.NDOObjectState == NDOObjectState.Created || relObj.NDOObjectState == NDOObjectState.Transient)
782 ····························&& GetClass(pc).Oid.HasAutoincrementedColumn && GetClass(relObj).Oid.HasAutoincrementedColumn)
783 ························{
784 ····························if (mappings.GetUpdateOrder(pc.GetType())
785 ································< mappings.GetUpdateOrder(relObj.GetType()))
786 ································createdDirectObjects.Add(pc);
787 ····························else
788 ································createdDirectObjects.Add( relObj );
789 ························}
790 ····················}
791 ····················if (r.Multiplicity == RelationMultiplicity.List)
792 ····················{
793 ························CreateAddedObjectRow(pc, r, relObj, r.Composition);
794 ····················}
795 ················}
796 ················else
797 ················{
798 ····················// Adding an object, which was removed in the same transaction, cancels the deletion.
799 ····················MappingTableEntry deleteEntry = FindMappingTableEntry(pc, r, relObj);
800 ····················if (deleteEntry != null)
801 ························createdMappingTableObjects.Remove(deleteEntry);
802 ····················else
803 ························createdMappingTableObjects.Add(new MappingTableEntry(pc, relObj, r));
804 ················}
805 ················if(r.Bidirectional)
806 ················{
807 ····················if (r.Multiplicity == RelationMultiplicity.List && mappings.GetRelationField(relObj, r.ForeignRelation.FieldName) == null)
808 ····················{
809 ························if ( r.ForeignRelation.Multiplicity == RelationMultiplicity.Element )
810 ····························mappings.SetRelationField(relObj, r.ForeignRelation.FieldName, pc);
811 ····················}
812 ····················else if ( !addLock.IsLocked( pc ) )
813 ····················{
814 ························PatchForeignRelation( pc, r, relObj );
815 ····················}
816 ················}
817
818 ················this.relationChanges.Add( new RelationChangeRecord( pc, relObj, r.FieldName, true ) );
819 ············}
820 ············finally
821 ············{
822 ················addLock.Unlock(relObj);
823 ················//Debug.Unindent();
824 ············}
825 ········}
826
827 ········/// <summary>
828 ········/// Returns an integer value which determines the rank of the given type in the update order list.
829 ········/// </summary>
830 ········/// <param name="t">The type to determine the update order.</param>
831 ········/// <returns>An integer value determining the rank of the given type in the update order list.</returns>
832 ········/// <remarks>
833 ········/// This method is used by NDO for diagnostic purposes. There is no value in using this method in user code.
834 ········/// </remarks>
835 ········public int GetUpdateRank(Type t)
836 ········{
837 ············return mappings.GetUpdateOrder(t);
838 ········}
839
840 ········/// <summary>
841 ········/// Add a related object to the specified object.
842 ········/// </summary>
843 ········/// <param name="pc">the parent object</param>
844 ········/// <param name="r">the relation mapping info</param>
845 ········/// <param name="relObj">the related object that should be added</param>
846 ········protected virtual void AddRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
847 ········{
848 ············//············string idstr;
849 ············//············if (relObj.NDOObjectId == null)
850 ············//················idstr = relObj.GetType().ToString();
851 ············//············else
852 ············//················idstr = relObj.NDOObjectId.Dump();
853 ············//Debug.WriteLine("AddRelatedObject " + pc.NDOObjectId.Dump() + " " + idstr);
854 ············//Debug.Indent();
855
856 ············Class relClass = GetClass(relObj);
857 ············bool isDependent = relClass.Oid.IsDependent;
858
859 ············// Do some checks to guarantee that the assignment is correct
860 ············if(r.Composition)
861 ············{
862 ················if(relObj.NDOObjectState != NDOObjectState.Transient)
863 ················{
864 ····················throw new NDOException(58, "Can only add transient objects in Composite relation " + pc.GetType().FullName + "->" + r.ReferencedTypeName + ".");
865 ················}
866 ············}
867 ············else
868 ············{
869 ················if(relObj.NDOObjectState == NDOObjectState.Transient && !isDependent)
870 ················{
871 ····················throw new NDOException(59, "Can only add persistent objects in Assoziation " + pc.GetType().FullName + "->" + r.ReferencedTypeName + ".");
872 ················}
873 ············}
874
875 ············if(!r.ReferencedType.IsAssignableFrom(relObj.GetType()))
876 ············{
877 ················throw new NDOException(60, "AddRelatedObject: Related object must be assignable to type: " + r.ReferencedTypeName + ". Assigned object was: " + relObj.NDOObjectId.Dump() + " Type = " + relObj.GetType());
878 ············}
879
880 ············InternalAddRelatedObject(pc, r, relObj, false);
881
882 ········}
883
884 ········private void CheckDependentKeyPreconditions(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj, Class relClass)
885 ········{
886 ············// Need to patch pc into the relation relObj->pc, because
887 ············// the oid is built on base of this information
888 ············// The second relation has to be set before adding relObj
889 ············// to the relation list.
890 ············PatchForeignRelation(pc, r, relObj);
891 ············IPersistenceCapable parent;
892 ············foreach (Relation oidRelation in relClass.Oid.Relations)
893 ············{
894 ················parent = (IPersistenceCapable)mappings.GetRelationField(relObj, oidRelation.FieldName);
895 ················if (parent == null)
896 ····················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.");
897 ················if (parent.NDOObjectState == NDOObjectState.Transient)
898 ····················throw new NDOException(59, "Can only add persistent objects in Assoziation " + relClass.FullName + "." + oidRelation.FieldName + ". Make the object of type " + parent.GetType().FullName + " persistent.");
899
900 ············}
901 ········}
902
903
904 ········/// <summary>
905 ········/// Remove a related object from the specified object.
906 ········/// </summary>
907 ········/// <param name="pc">the parent object</param>
908 ········/// <param name="fieldName">Field name of the relation</param>
909 ········/// <param name="relObj">the related object that should be removed</param>
910 ········internal virtual void RemoveRelatedObject(IPersistenceCapable pc, string fieldName, IPersistenceCapable relObj)
911 ········{
912 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient);
913 ············Relation r = mappings.FindRelation(pc, fieldName);
914 ············InternalRemoveRelatedObject(pc, r, relObj, true);
915 ········}
916
917 ········/// <summary>
918 ········/// Registers a listener which will be notified, if a new connection is opened.
919 ········/// </summary>
920 ········/// <param name="listener">Delegate of a listener function</param>
921 ········/// <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>
922 ········public virtual void RegisterConnectionListener(OpenConnectionListener listener)
923 ········{
924 ············this.openConnectionListener = listener;
925 ········}
926
927 ········internal string OnNewConnection(NDO.Mapping.Connection conn)
928 ········{
929 ············if (openConnectionListener != null)
930 ················return openConnectionListener(conn);
931 ············return conn.Name;
932 ········}
933
934
935 ········/*
936 ········doCommit should be:
937 ········
938 ····················Query····Save····Save(true)
939 ········Optimistic····1········1········0
940 ········Pessimistic····0········1········0
941 ············
942 ········Deferred Mode············
943 ····················Query····Save····Save(true)
944 ········Optimistic····0········1········0
945 ········Pessimistic····0········1········0
946 ········ */
947
948 ········internal void CheckEndTransaction(bool doCommit)
949 ········{
950 ············CheckEndTransactionAsync( doCommit ).ConfigureAwait( false ).GetAwaiter().GetResult();
951 ········}
952
953 ········internal async Task CheckEndTransactionAsync( bool doCommit, CancellationToken cancellationToken = default )
954 ········{
955 ············if (doCommit)
956 ············{
957 ················await TransactionScope.CompleteAsync( cancellationToken ).ConfigureAwait( false );
958 ············}
959 ········}
960
961 ········internal Task CheckTransactionAsync( IPersistenceHandlerBase handler, Type t, CancellationToken cancellationToken = default )
962 ········{
963 ············return CheckTransactionAsync( handler, this.GetClass( t ).Connection, cancellationToken );
964 ········}
965
966 ········int activeOperation;
967 ········readonly AsyncLocal<bool> ownsOperation = new AsyncLocal<bool>();
968
969 ········/// <summary>
970 ········/// Marks the begin of an operation with database access. Detects concurrent usage of the PersistenceManager.
971 ········/// </summary>
972 ········/// <param name="caller">The name of the calling method</param>
973 ········/// <returns>An object, which marks the end of the operation if disposed.</returns>
974 ········/// <remarks>
975 ········/// Nested calls in the same logical flow (e.g. lazy loading in an OnSaving handler) are allowed.
976 ········/// The AsyncLocal flows with the ExecutionContext into all awaited calls, but not back to the caller of an async method.
977 ········/// So two concurrently started tasks don't share the ownership.
978 ········/// </remarks>
979 ········internal OperationGuard EnterOperation( [CallerMemberName] string caller = null )
980 ········{
981 ············if (this.ownsOperation.Value)
982 ················return default;··// Nested call in the same logical flow
983 ············if (Interlocked.CompareExchange( ref this.activeOperation, 1, 0 ) != 0)
984 ················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." );
985 ············this.ownsOperation.Value = true;
986 ············return new OperationGuard( this );
987 ········}
988
989 ········internal readonly struct OperationGuard : IDisposable
990 ········{
991 ············readonly PersistenceManager pm;
992
993 ············public OperationGuard( PersistenceManager pm )
994 ············{
995 ················this.pm = pm;
996 ············}
997
998 ············public void Dispose()
999 ············{
1000 ················if (this.pm == null)
1001 ····················return;··// Nested call: nothing to release
1002 ················this.pm.ownsOperation.Value = false;
1003 ················Volatile.Write( ref this.pm.activeOperation, 0 );
1004 ············}
1005 ········}
1006
1007 ········/// <summary>
1008 ········/// Each and every database operation has to be preceded by a call to this function.
1009 ········/// </summary>
1010 ········internal async Task CheckTransactionAsync( IPersistenceHandlerBase handler, Connection ndoConn, CancellationToken cancellationToken = default )
1011 ········{
1012 ············await TransactionScope.CheckTransactionAsync( cancellationToken ).ConfigureAwait( false );
1013 ············
1014 ············if (handler.Connection == null)
1015 ············{
1016 ················handler.Connection = await TransactionScope.GetConnectionAsync(ndoConn, () =>
1017 ················{
1018 ····················IProvider p = ndoConn.Parent.GetProvider( ndoConn );
1019 ····················string connStr = this.OnNewConnection( ndoConn );
1020 ····················var connection = p.NewConnection( connStr );
1021 ····················if (connection == null)
1022 ························throw new NDOException( 119, $"Can't construct connection for {connStr}. The provider returns null." );
1023 ····················LogIfVerbose( $"Creating a connection object for {ndoConn.DisplayName}" );
1024 ····················return connection;
1025 ················}, cancellationToken ).ConfigureAwait( false );
1026 ············}
1027
1028 ············if (TransactionMode != TransactionMode.None)
1029 ············{
1030 ················handler.Transaction = TransactionScope.GetTransaction( ndoConn.ID );
1031 ············}
1032
1033 ············// There are tests with a handler mock that always returns zero for the Connection property.
1034 ············if (handler.Connection != null && handler.Connection.State != ConnectionState.Open)
1035 ············{
1036 ················await handler.Connection.OpenAsync( cancellationToken ).ConfigureAwait( false );
1037 ················var serverId = ndoConn.Provider.GetConnectionId( handler.Connection );
1038 ················LogIfVerbose( $"Opening connection {serverId} = '{ndoConn.DisplayName}'" );
1039 ············}
1040 ········}
1041
1042 ········/// <summary>
1043 ········/// Event Handler for the ConcurrencyError event of the IPersistenceHandler.
1044 ········/// We try to tell the object which caused the concurrency exception, that a collicion occured.
1045 ········/// This is possible if there is a listener for the CollisionEvent.
1046 ········/// Else we throw an exception.
1047 ········/// </summary>
1048 ········/// <param name="ex">Concurrency Exception which was catched during update.</param>
1049 ········private void OnConcurrencyError(System.Data.DBConcurrencyException ex)
1050 ········{
1051 ············DataRow row = ex.Row;
1052 ············if (row == null || CollisionEvent == null || CollisionEvent.GetInvocationList().Length == 0)
1053 ················throw(ex);
1054 ············if (row.RowState == DataRowState.Detached)
1055 ················return;
1056 ············foreach (Cache.Entry e in cache.LockedObjects)
1057 ············{
1058 ················if (e.row == row)
1059 ················{
1060 ····················CollisionEvent(e.pc);
1061 ····················return;
1062 ················}
1063 ············}
1064 ············throw ex;
1065 ········}
1066
1067
1068 ········private void ReadObject(IPersistenceCapable pc, DataRow row, string[] fieldNames, int startIndex)
1069 ········{
1070 ············Class cl = GetClass(pc);
1071 ············string[] etypes = cl.EmbeddedTypes.ToArray();
1072 ············Dictionary<string,MemberInfo> persistentFields = null;
1073 ············if (etypes.Length > 0)
1074 ············{
1075 ················FieldMap fm = new FieldMap(cl);
1076 ················persistentFields = fm.PersistentFields;
1077 ············}
1078 ············foreach(string s in etypes)
1079 ············{
1080 ················try
1081 ················{
1082 ····················NDO.Mapping.Field f = cl.FindField(s);
1083 ····················if (f == null)
1084 ························continue;
1085 ····················object o = row[f.Column.Name];
1086 ····················string[] arr = s.Split('.');
1087 ····················// Suche Embedded Type-Feld mit Namen arr[0]
1088 ····················BaseClassReflector bcr = new BaseClassReflector(pc.GetType());
1089 ····················FieldInfo parentFi = bcr.GetField(arr[0], BindingFlags.NonPublic | BindingFlags.Instance);
1090 ····················// Hole das Embedded Object
1091 ····················object parentOb = parentFi.GetValue(pc);
1092
1093 ····················if (parentOb == null)
1094 ························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]));
1095
1096 ····················// Suche darin das Feld mit Namen Arr[1]
1097
1098 ····················FieldInfo childFi = parentFi.FieldType.GetField(arr[1], BindingFlags.NonPublic | BindingFlags.Instance);
1099 ····················Type childType = childFi.FieldType;
1100
1101 ····················// Don't initialize value types, if DBNull is stored in the field.
1102 ····················// Exception: DateTime and Guid.
1103 ····················if (o == DBNull.Value && childType.IsValueType
1104 ························&& childType != typeof(Guid)
1105 ························&& childType != typeof(DateTime))
1106 ························continue;
1107
1108 ····················if (childType == typeof(DateTime))
1109 ····················{
1110 ························if (o == DBNull.Value)
1111 ····························o = DateTime.MinValue;
1112 ····················}
1113 ····················if (childType.IsClass)
1114 ····················{
1115 ························if (o == DBNull.Value)
1116 ····························o = null;
1117 ····················}
1118
1119 ····················if (childType == typeof (Guid))
1120 ····················{
1121 ························if (o == DBNull.Value)
1122 ····························o = Guid.Empty;
1123 ························if (o is string)
1124 ························{
1125 ····························childFi.SetValue(parentOb, new Guid((string)o));
1126 ························}
1127 ························else if (o is Guid)
1128 ························{
1129 ····························childFi.SetValue(parentOb, o);
1130 ························}
1131 ························else if (o is byte[])
1132 ························{
1133 ····························childFi.SetValue(parentOb, new Guid((byte[])o));
1134 ························}
1135 ························else
1136 ····························throw new Exception(string.Format("Can't convert Guid field to column type {0}.", o.GetType().FullName));
1137 ····················}
1138 ····················else if (childType.IsSubclassOf(typeof(System.Enum)))
1139 ····················{
1140 ························object childOb = childFi.GetValue(parentOb);
1141 ························FieldInfo valueFi = childType.GetField("value__");
1142 ························valueFi.SetValue(childOb, o);
1143 ························childFi.SetValue(parentOb, childOb);
1144 ····················}
1145 ····················else
1146 ····················{
1147 ························childFi.SetValue(parentOb, o);
1148 ····················}
1149 ················}
1150 ················catch (Exception ex)
1151 ················{
1152 ····················string msg = "Error while writing the embedded object {0} of an object of type {1}. Check your mapping file.\n{2}";
1153
1154 ····················throw new NDOException(68, string.Format(msg, s, pc.GetType().FullName, ex.Message), ex);
1155 ················}
1156
1157 ············}
1158 ············
1159 ············try
1160 ············{
1161 ················if (cl.HasEncryptedFields)
1162 ················{
1163 ····················foreach (var field in cl.Fields.Where( f => f.Encrypted ))
1164 ····················{
1165 ························string name = field.Column.Name;
1166 ························string s = (string) row[name];
1167 ························string es = AesHelper.Decrypt( s, EncryptionKey );
1168 ························row[name] = es;
1169 ····················}
1170 ················}
1171 ················pc.NDORead(row, fieldNames, startIndex);
1172 ············}
1173 ············catch (Exception ex)
1174 ············{
1175 ················throw new NDOException(69, "Error while writing to a field of an object of type " + pc.GetType().FullName + ". Check your mapping file.\n"
1176 ····················+ ex.Message, ex);
1177 ············}
1178 ········}
1179
1180 ········/// <summary>
1181 ········/// Executes a sql script to generate the database tables.
1182 ········/// The function will execute any sql statements in the script
1183 ········/// which are valid according to the
1184 ········/// rules of the underlying database. Result sets are ignored.
1185 ········/// </summary>
1186 ········/// <param name="scriptFile">The script file to execute.</param>
1187 ········/// <param name="conn">A connection object, containing the connection
1188 ········/// string to the database, which should be altered.</param>
1189 ········/// <returns>A string array with error messages or the string "OK" for each of the statements in the file.</returns>
1190 ········/// <remarks>
1191 ········/// If the Connection object is invalid or null, a NDOException with ErrorNumber 44 will be thrown.
1192 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1193 ········/// Their message property will appear in the result array.
1194 ········/// If the script doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1195 ········/// </remarks>
1196 ········public string[] BuildDatabase( string scriptFile, Connection conn )
1197 ········{
1198 ············return BuildDatabase( scriptFile, conn, Encoding.UTF8 );
1199 ········}
1200
1201 ········/// <summary>
1202 ········/// Executes a sql script to generate the database tables.
1203 ········/// The function will execute any sql statements in the script
1204 ········/// which are valid according to the
1205 ········/// rules of the underlying database. Result sets are ignored.
1206 ········/// </summary>
1207 ········/// <param name="scriptFile">The script file to execute.</param>
1208 ········/// <param name="conn">A connection object, containing the connection
1209 ········/// string to the database, which should be altered.</param>
1210 ········/// <param name="encoding">The encoding of the script file. Default is UTF8.</param>
1211 ········/// <returns>A string array with error messages or the string "OK" for each of the statements in the file.</returns>
1212 ········/// <remarks>
1213 ········/// If the Connection object is invalid or null, a NDOException with ErrorNumber 44 will be thrown.
1214 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1215 ········/// Their message property will appear in the result array.
1216 ········/// If the script doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1217 ········/// </remarks>
1218 ········public string[] BuildDatabase(string scriptFile, Connection conn, Encoding encoding)
1219 ········{
1220 ············StreamReader sr = new StreamReader(scriptFile, encoding);
1221 ············string s = sr.ReadToEnd();
1222 ············sr.Close();
1223 ············string[] arr = s.Split(';');
1224 ············string last = arr[arr.Length - 1];
1225 ············bool lastInvalid = (last == null || last.Trim() == string.Empty);
1226 ············string[] result = new string[arr.Length - (lastInvalid ? 1 : 0)];
1227 ············using (var handler = GetSqlPassThroughHandler())
1228 ············{
1229 ················int i = 0;
1230 ················string ok = "OK";
1231 ················foreach (string statement in arr)
1232 ················{
1233 ····················if (statement != null && statement.Trim() != string.Empty)
1234 ····················{
1235 ························try
1236 ························{
1237 ····························handler.Execute(statement);
1238 ····························result[i] = ok;
1239 ························}
1240 ························catch (Exception ex)
1241 ························{
1242 ····························result[i] = ex.Message;
1243 ························}
1244 ····················}
1245 ····················i++;
1246 ················}
1247 ················CheckEndTransaction(true);
1248 ············}
1249 ············return result;
1250 ········}
1251
1252 ········/// <summary>
1253 ········/// Executes a sql script to generate the database tables.
1254 ········/// The function will execute any sql statements in the script
1255 ········/// which are valid according to the
1256 ········/// rules of the underlying database. Result sets are ignored.
1257 ········/// </summary>
1258 ········/// <param name="scriptFile">The script file to execute.</param>
1259 ········/// <returns></returns>
1260 ········/// <remarks>
1261 ········/// This function takes the first Connection object in the Connections list
1262 ········/// of the Mapping file und executes the script using that connection.
1263 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1264 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1265 ········/// Their message property will appear in the result array.
1266 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1267 ········/// </remarks>
1268 ········public string[] BuildDatabase(string scriptFile)
1269 ········{
1270 ············if (!File.Exists(scriptFile))
1271 ················throw new NDOException(48, "Script file " + scriptFile + " doesn't exist.");
1272 ············if (!this.mappings.Connections.Any())
1273 ················throw new NDOException(48, "Mapping file doesn't define a connection.");
1274 ············Connection conn = new Connection( this.mappings );
1275 ············Connection originalConnection = (Connection)this.mappings.Connections.First();
1276 ············conn.Name = OnNewConnection( originalConnection );
1277 ············conn.Type = originalConnection.Type;
1278 ············//Connection conn = (Connection) this.mappings.Connections[0];
1279 ············return BuildDatabase(scriptFile, conn);
1280 ········}
1281
1282 ········/// <summary>
1283 ········/// Executes a sql script to generate the database tables.
1284 ········/// The function will execute any sql statements in the script
1285 ········/// which are valid according to the
1286 ········/// rules of the underlying database. Result sets are ignored.
1287 ········/// </summary>
1288 ········/// <returns>
1289 ········/// A string array, containing the error messages produced by the statements
1290 ········/// contained in the script.
1291 ········/// </returns>
1292 ········/// <remarks>
1293 ········/// The sql script is assumed to be the executable name of the entry assembly with the
1294 ········/// extension .ndo.sql. Use BuildDatabase(string) to provide a path to a script.
1295 ········/// If the executable name can't be determined a NDOException with ErrorNumber 49 will be thrown.
1296 ········/// This function takes the first Connection object in the Connections list
1297 ········/// of the Mapping file und executes the script using that connection.
1298 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1299 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1300 ········/// Their message property will appear in the result array.
1301 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1302 ········/// </remarks>
1303 ········public string[] BuildDatabase()
1304 ········{
1305 ············Assembly ass = Assembly.GetEntryAssembly();
1306 ············if (ass == null)
1307 ················throw new NDOException(49, "Can't determine the path of the entry assembly - please pass a sql script path as argument to BuildDatabase.");
1308 ············string file = Path.ChangeExtension(ass.Location, ".ndo.sql");
1309 ············return BuildDatabase(file);
1310 ········}
1311
1312 ········/// <summary>
1313 ········/// Gets a SqlPassThroughHandler object which can be used to execute raw Sql statements.
1314 ········/// </summary>
1315 ········/// <param name="conn">Optional: The NDO-Connection to the database to be used.</param>
1316 ········/// <returns>An ISqlPassThroughHandler implementation</returns>
1317 ········public ISqlPassThroughHandler GetSqlPassThroughHandler( Connection conn = null )
1318 ········{
1319 ············if (!this.mappings.Connections.Any())
1320 ················throw new NDOException( 48, "Mapping file doesn't define a connection." );
1321 ············if (conn == null)
1322 ············{
1323 ················conn = new Connection( this.mappings );
1324 ················Connection originalConnection = (Connection) this.mappings.Connections.First();
1325 ················conn.Name = OnNewConnection( originalConnection );
1326 ················conn.Type = originalConnection.Type;
1327 ············}
1328
1329 ············return new SqlPassThroughHandler( this, conn );
1330 ········}
1331
1332 ········/// <summary>
1333 ········/// Gets a SqlPassThroughHandler object which can be used to execute raw Sql statements.
1334 ········/// </summary>
1335 ········/// <param name="predicate">A predicate defining which connection has to be used.</param>
1336 ········/// <returns>An ISqlPassThroughHandler implementation</returns>
1337 ········public ISqlPassThroughHandler GetSqlPassThroughHandler( Func<Connection, bool> predicate )
1338 ········{
1339 ············if (!this.mappings.Connections.Any())
1340 ················throw new NDOException( 48, "The Mapping file doesn't define a connection." );
1341 ············Connection conn = this.mappings.Connections.FirstOrDefault( predicate );
1342 ············if (conn == null)
1343 ················throw new NDOException( 48, "The Mapping file doesn't define a connection with this predicate." );
1344 ············return GetSqlPassThroughHandler( conn );
1345 ········}
1346
1347 ········/// <summary>
1348 ········/// Executes a xml script to generate the database tables.
1349 ········/// The function will generate and execute sql statements to perform
1350 ········/// the changes described by the xml.
1351 ········/// </summary>
1352 ········/// <returns></returns>
1353 ········/// <remarks>
1354 ········/// The script file is the first file found with the search string [AssemblyNameWithoutExtension].ndodiff.[SchemaVersion].xml.
1355 ········/// If several files match the search string biggest file name in the default sort order will be executed.
1356 ········/// This function takes the first Connection object in the Connections list
1357 ········/// of the Mapping file und executes the script using that connection.
1358 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1359 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1360 ········/// Their message property will appear in the result string array.
1361 ········/// If no script file exists, a NDOException with ErrorNumber 48 will be thrown.
1362 ········/// Note that an additional command is executed, which will update the NDOSchemaVersion entry.
1363 ········/// </remarks>
1364 ········public string[] PerformSchemaTransitions()
1365 ········{
1366 ············Assembly ass = Assembly.GetEntryAssembly();
1367 ············if (ass == null)
1368 ················throw new NDOException(49, "Can't determine the path of the entry assembly - please pass a sql script path as argument to PerformSchemaTransitions.");
1369 ············string mask = Path.GetFileNameWithoutExtension( ass.Location ) + ".ndodiff.*.xml";
1370 ············List<string> fileNames = Directory.GetFiles( Path.GetDirectoryName( ass.Location ), mask ).ToList();
1371 ············if (fileNames.Count == 0)
1372 ················return new String[] { String.Format( "No xml script file with a name like {0} found.", mask ) };
1373 ············if (fileNames.Count > 1)
1374 ················fileNames.Sort( ( fn1, fn2 ) => CompareFileName( fn1, fn2 ) );
1375 ············return PerformSchemaTransitions( fileNames[0] );
1376 ········}
1377
1378
1379 ········/// <summary>
1380 ········/// Executes a xml script to generate the database tables.
1381 ········/// The function will generate and execute sql statements to perform
1382 ········/// the changes described by the xml.
1383 ········/// </summary>
1384 ········/// <param name="scriptFile">The script file to execute.</param>
1385 ········/// <returns></returns>
1386 ········/// <remarks>
1387 ········/// This function takes the first Connection object in the Connections list
1388 ········/// of the Mapping file und executes the script using that connection.
1389 ········/// If no default connection exists, a NDOException with ErrorNumber 44 will be thrown.
1390 ········/// Any exceptions thrown while executing a statement in the script, will be caught.
1391 ········/// Their message property will appear in the result string array.
1392 ········/// If the script file doesn't exist, a NDOException with ErrorNumber 48 will be thrown.
1393 ········/// Note that an additional command is executed, which will update the NDOSchemaVersion entry.
1394 ········/// </remarks>
1395 ········public string[] PerformSchemaTransitions(string scriptFile)
1396 ········{
1397 ············if (!File.Exists(scriptFile))
1398 ················throw new NDOException(48, "Script file " + scriptFile + " doesn't exist.");
1399
1400 ············if (!this.mappings.Connections.Any())
1401 ················throw new NDOException(48, "Mapping file doesn't define any connection.");
1402 ············Connection conn = new Connection( mappings );
1403 ············Connection originalConnection = mappings.Connections.First();
1404 ············conn.Name = OnNewConnection( originalConnection );
1405 ············conn.Type = originalConnection.Type;
1406 ············return PerformSchemaTransitions(scriptFile, conn);
1407 ········}
1408
1409
1410 ········int CompareFileName( string fn1, string fn2)
1411 ········{
1412 ············Regex regex = new Regex( @"ndodiff\.(.+)\.xml" );
1413 ············Match match = regex.Match( fn1 );
1414 ············string v1 = match.Groups[1].Value;
1415 ············match = regex.Match( fn2 );
1416 ············string v2 = match.Groups[1].Value;
1417 ············return new Version( v2 ).CompareTo( new Version( v1 ) );
1418 ········}
1419
1420 ········Guid[] GetSchemaIds(Connection ndoConn, string schemaName, IProvider provider)
1421 ········{
1422 ············var connection = provider.NewConnection( ndoConn.Name );
1423 ············var resultList = new List<Guid>();
1424
1425 ············using (var handler = GetSqlPassThroughHandler())
1426 ············{
1427 ················string[] TableNames = provider.GetTableNames( connection );
1428 ················if (TableNames.Any( t => String.Compare( t, "NDOSchemaIds", true ) == 0 ))
1429 ················{
1430 ····················var schemaIds = provider.GetQualifiedTableName("NDOSchemaIds");
1431 ····················var sn = provider.GetQuotedName("SchemaName");
1432 ····················var id = provider.GetQuotedName("Id");
1433 ····················string sql = $"SELECT {id} from {schemaIds} WHERE {sn} ";
1434 ····················if (String.IsNullOrEmpty(schemaName))
1435 ························sql += "IS NULL;";
1436 ····················else
1437 ························sql += $"LIKE '{schemaName}'";
1438
1439 ····················using(IDataReader dr = handler.Execute(sql, true))
1440 ····················{
1441 ························while (dr.Read())
1442 ····························resultList.Add( dr.GetGuid( 0 ) );
1443 ····················}
1444 ················}
1445 ················else
1446 ················{
1447 ····················SchemaTransitionGenerator schemaTransitionGenerator = new SchemaTransitionGenerator( ProviderFactory, ndoConn.Type, this.mappings );
1448 ····················var gt = typeof(Guid);
1449 ····················var gtype = $"{gt.FullName},{ new AssemblyName( gt.Assembly.FullName ).Name }";
1450 ····················var st = typeof(String);
1451 ····················var stype = $"{st.FullName},{ new AssemblyName( st.Assembly.FullName ).Name }";
1452 ····················var dt = typeof(DateTime);
1453 ····················var dtype = $"{st.FullName},{ new AssemblyName( st.Assembly.FullName ).Name }";
1454 ····················string transition = $@"<NdoSchemaTransition>
1455 ····<CreateTable name=""NDOSchemaIds"">
1456 ······<CreateColumn name=""SchemaName"" type=""{stype}"" allowNull=""True"" />
1457 ······<CreateColumn name=""Id"" type=""{gtype}"" size=""36"" isPrimary=""True"" />
1458 ······<CreateColumn name=""InsertTime"" type=""{dtype}"" size=""36"" />
1459 ····</CreateTable>
1460 </NdoSchemaTransition>";
1461 ····················XElement transitionElement = XElement.Parse(transition);
1462
1463 ····················string sql = schemaTransitionGenerator.Generate( transitionElement );
1464 ····················handler.Execute(sql);
1465 ················}
1466 ················handler.CommitTransaction();
1467 ············}
1468
1469 ············return resultList.ToArray();
1470 ········}
1471
1472 ········/// <summary>
1473 ········/// Executes a xml script to generate the database tables.
1474 ········/// The function will generate and execute sql statements to perform
1475 ········/// the changes described by the xml.
1476 ········/// </summary>
1477 ········/// <param name="scriptFile">The xml script file.</param>
1478 ········/// <param name="ndoConn">The connection to be used to perform the schema changes.</param>
1479 ········/// <returns>A list of strings about the states of the different schema change commands.</returns>
1480 ········/// <remarks>Note that an additional command is executed, which will update the NDOSchemaVersion entry.</remarks>
1481 ········public string[] PerformSchemaTransitions(string scriptFile, Connection ndoConn)
1482 ········{
1483 ············string schemaName = null;
1484 ············// Gespeicherte Version ermitteln.
1485 ············XElement transitionElements = XElement.Load( scriptFile );
1486 ············if (transitionElements.Attribute( "schemaName" ) != null)
1487 ················schemaName = transitionElements.Attribute( "schemaName" ).Value;
1488
1489 ············IProvider provider = this.mappings.GetProvider( ndoConn );
1490 ············var installedIds = GetSchemaIds( ndoConn, schemaName, provider );
1491 ············var newIds = new List<Guid>();
1492 ············SchemaTransitionGenerator schemaTransitionGenerator = new SchemaTransitionGenerator( ProviderFactory, ndoConn.Type, this.mappings );
1493
1494 ············// dtLiteral contains the leading and trailing quotes
1495 ············var dtLiteral = provider.GetSqlLiteral( DateTime.Now );
1496 ············var ndoSchemaIds = provider.GetQualifiedTableName("NDOSchemaIds");
1497 ············var schName = provider.GetQuotedName("SchemaName");
1498 ············var idCol = provider.GetQuotedName("Id");
1499 ············var insertTime = provider.GetQuotedName("InsertTime");
1500 ············var results = new List<string>();
1501
1502 ············// Each transitionElement gets it's own transaction.
1503 ············// The insert into NDOSchemaIds is part of the transaction.
1504 ············// If an error occurs, InternalPerformSchemaTransitions aborts the transaction.
1505 ············foreach (XElement transitionElement in transitionElements.Elements( "NdoSchemaTransition" ))
1506 ············{
1507 ················var id = transitionElement.Attribute("id")?.Value;
1508 ················if (id == null)
1509 ····················continue;
1510 ················var gid = new Guid(id);
1511 ················if (installedIds.Contains( gid ))
1512 ····················continue;
1513
1514 ················var sb = new StringBuilder();
1515 ················sb.Append( schemaTransitionGenerator.Generate( transitionElement ) );
1516 ················newIds.Add( gid );
1517
1518 ················if (schemaName != null)
1519 ····················sb.Append( $"INSERT INTO {ndoSchemaIds} ({schName},{idCol},{insertTime}) VALUES ('{schemaName}','{gid}',{dtLiteral});" );
1520 ················else
1521 ····················sb.Append( $"INSERT INTO {ndoSchemaIds} ({schName},{idCol},{insertTime}) VALUES (NULL,'{gid}',{dtLiteral});" );
1522
1523 ················results.AddRange( InternalPerformSchemaTransitions( ndoConn, sb.ToString() ) );
1524 ············}
1525
1526 ············return results.ToArray();
1527 ········}
1528
1529 ········private string[] InternalPerformSchemaTransitions( Connection ndoConn, string sql )
1530 ········{
1531 ············string[] arr = sql.Split( ';' );
1532
1533 ············string last = arr[arr.Length - 1];
1534 ············bool lastInvalid = (last == null || last.Trim() == string.Empty);
1535 ············string[] result = new string[arr.Length - (lastInvalid ? 1 : 0)];
1536 ············int i = 0;
1537 ············string ok = "OK";
1538 ············using (var handler = GetSqlPassThroughHandler())
1539 ············{
1540 ················handler.BeginTransaction();
1541 ················var doCommit = true;
1542 ················foreach (string statement in arr)
1543 ················{
1544 ····················if (!String.IsNullOrWhiteSpace(statement))
1545 ····················{
1546 ························try
1547 ························{
1548 ····························handler.Execute( statement.Trim() );
1549 ····························result[i] = ok;
1550 ························}
1551 ························catch (Exception ex)
1552 ························{
1553 ····························result[i] = ex.Message;
1554 ····························doCommit = false;
1555 ························}
1556 ····················}
1557 ····················i++;
1558 ················}
1559 ················if (doCommit)
1560 ····················handler.CommitTransaction();
1561 ················else
1562 ····················AbortTransaction();
1563 ············}
1564
1565 ············return result;
1566 ········}
1567 ········
1568 ········/// <summary>
1569 ········/// Transfers Data from the object to the DataRow
1570 ········/// </summary>
1571 ········/// <param name="pc"></param>
1572 ········/// <param name="row"></param>
1573 ········/// <param name="fieldNames"></param>
1574 ········/// <param name="startIndex"></param>
1575 ········protected virtual void WriteObject(IPersistenceCapable pc, DataRow row, string[] fieldNames, int startIndex)
1576 ········{
1577 ············Class cl = GetClass( pc );
1578 ············try
1579 ············{
1580 ················pc.NDOWrite(row, fieldNames, startIndex);
1581 ················if (cl.HasEncryptedFields)
1582 ················{
1583 ····················foreach (var field in cl.Fields.Where( f => f.Encrypted ))
1584 ····················{
1585 ························string name = field.Column.Name;
1586 ························string s = (string) row[name];
1587 ························string es = AesHelper.Encrypt( s, EncryptionKey );
1588 ························row[name] = es;
1589 ····················}
1590 ················}
1591 ············}
1592 ············catch (Exception ex)
1593 ············{
1594 ················throw new NDOException(70, "Error while reading a field of an object of type " + pc.GetType().FullName + ". Check your mapping file.\n"
1595 ····················+ ex.Message, ex);
1596 ············}
1597
1598 ············if (cl.TypeNameColumn != null)
1599 ············{
1600 ················Type t = pc.GetType();
1601 ················row[cl.TypeNameColumn.Name] = t.FullName + "," + t.Assembly.GetName().Name;
1602 ············}
1603
1604 ············var etypes = cl.EmbeddedTypes;
1605 ············foreach(string s in etypes)
1606 ············{
1607 ················try
1608 ················{
1609 ····················NDO.Mapping.Field f = cl.FindField(s);
1610 ····················if (f == null)
1611 ························continue;
1612 ····················string[] arr = s.Split('.');
1613 ····················// Suche Feld mit Namen arr[0] als object
1614 ····················BaseClassReflector bcr = new BaseClassReflector(pc.GetType());
1615 ····················FieldInfo parentFi = bcr.GetField(arr[0], BindingFlags.NonPublic | BindingFlags.Instance);
1616 ····················Object parentOb = parentFi.GetValue(pc);
1617 ····················if (parentOb == null)
1618 ························throw new Exception(String.Format("The field {0} is null. Initialize the field in your default constructor.", arr[0]));
1619 ····················// Suche darin das Feld mit Namen Arr[1]
1620 ····················FieldInfo childFi = parentFi.FieldType.GetField(arr[1], BindingFlags.NonPublic | BindingFlags.Instance);
1621 ····················object o = childFi.GetValue(parentOb);
1622 ····················if (o == null
1623 ························|| o is DateTime && (DateTime) o == DateTime.MinValue
1624 ························|| o is Guid && (Guid) o == Guid.Empty)
1625 ························o = DBNull.Value;
1626 ····················row[f.Column.Name] = o;
1627 ················}
1628 ················catch (Exception ex)
1629 ················{
1630 ····················string msg = "Error while reading the embedded object {0} of an object of type {1}. Check your mapping file.\n{2}";
1631
1632 ····················throw new NDOException(71, string.Format(msg, s, pc.GetType().FullName, ex.Message), ex);
1633 ················}
1634 ············}
1635 ········}
1636
1637 ········/// <summary>
1638 ········/// Check, if the specific field is loaded. If not, LoadData will be called.
1639 ········/// </summary>
1640 ········/// <param name="o">The parent object.</param>
1641 ········/// <param name="fieldOrdinal">A number to identify the field.</param>
1642 ········public virtual void LoadField(object o, int fieldOrdinal)
1643 ········{
1644 ············IPersistenceCapable pc = CheckPc(o);
1645 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
1646 ············{
1647 ················LoadState ls = pc.NDOLoadState;
1648 ················if (ls.FieldLoadState != null)
1649 ················{
1650 ····················if (ls.FieldLoadState[fieldOrdinal])
1651 ························return;
1652 ················}
1653 ················else
1654 ················{
1655 ····················ls.FieldLoadState = new BitArray( GetClass( pc ).Fields.Count() );
1656 ················}
1657 ················LoadData(o);
1658 ········}
1659 ········}
1660
1661 #pragma warning disable 419
1662 ········/// <summary>
1663 ········/// Load the data of a persistent object. This forces the transition of the object state from hollow to persistent.
1664 ········/// </summary>
1665 ········/// <param name="o">The hollow object.</param>
1666 ········/// <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>
1667 #pragma warning restore 419
1668 ········public void LoadData( object o )
1669 ········{
1670 ············LoadDataAsync( o ).ConfigureAwait( false ).GetAwaiter().GetResult();
1671 ········}
1672
1673 #pragma warning disable 419
1674 ········/// <summary>
1675 ········/// Load the data of a persistent object asynchronously. This forces the transition of the object state from hollow to persistent.
1676 ········/// </summary>
1677 ········/// <param name="o">The hollow object.</param>
1678 ········/// <param name="cancellationToken">A token to cancel the operation</param>
1679 ········/// <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>
1680 #pragma warning restore 419
1681 ········public virtual async Task LoadDataAsync( object o, CancellationToken cancellationToken = default )
1682 ········{
1683 ············using (EnterOperation())
1684 ············{
1685 ················await LoadDataInternalAsync( o, cancellationToken ).ConfigureAwait( false );
1686 ············}
1687 ········}
1688
1689 ········async Task LoadDataInternalAsync( object o, CancellationToken cancellationToken )
1690 ········{
1691 ············IPersistenceCapable pc = CheckPc(o);
1692 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Hollow, "Can only load hollow objects");
1693 ············if (pc.NDOObjectState != NDOObjectState.Hollow)
1694 ················return;
1695 ············Class cl = GetClass(pc);
1696 ············IQuery q;
1697 ············q = CreateOidQuery(pc, cl);
1698 ············cache.UpdateCache(pc); // Make sure the object is in the cache
1699
1700 ············var objects = await q.ExecuteAsync( cancellationToken ).ConfigureAwait( false );
1701 ············var count = objects.Count;
1702
1703 ············if (count > 1)
1704 ············{
1705 ················throw new NDOException( 72, "Load Data: " + count + " result objects with the same oid" );
1706 ············}
1707 ············else if (count == 0)
1708 ············{
1709 ················if (ObjectNotPresentEvent == null || !ObjectNotPresentEvent(pc))
1710 ················throw new NDOException( 72, "LoadData: Object " + pc.NDOObjectId.Dump() + " is not present in the database." );
1711 ············}
1712 ········}
1713
1714 ········/// <summary>
1715 ········/// Creates a new IQuery object for the given type
1716 ········/// </summary>
1717 ········/// <param name="t"></param>
1718 ········/// <param name="oql"></param>
1719 ········/// <param name="hollow"></param>
1720 ········/// <param name="queryLanguage"></param>
1721 ········/// <returns></returns>
1722 ········public IQuery NewQuery(Type t, string oql, bool hollow = false, QueryLanguage queryLanguage = QueryLanguage.NDOql)
1723 ········{
1724 ············Type template = typeof( NDOQuery<object> ).GetGenericTypeDefinition();
1725 ············Type qt = template.MakeGenericType( t );
1726 ············return (IQuery)Activator.CreateInstance( qt, this, oql, hollow, queryLanguage );
1727 ········}
1728
1729 ········private IQuery CreateOidQuery(IPersistenceCapable pc, Class cl)
1730 ········{
1731 ············ArrayList parameters = new ArrayList();
1732 ············string oql = "oid = {0}";
1733 ············IQuery q = NewQuery(pc.GetType(), oql, false);
1734 ············q.Parameters.Add( pc.NDOObjectId );
1735 ············q.AllowSubclasses = false;
1736 ············return q;
1737 ········}
1738
1739 ········/// <summary>
1740 ········/// Mark the object dirty. The current state is
1741 ········/// saved in a DataRow, which is stored in the DS. This is done, to allow easy rollback later. Also, the
1742 ········/// object is locked in the cache.
1743 ········/// </summary>
1744 ········/// <param name="pc"></param>
1745 ········internal virtual void MarkDirty(IPersistenceCapable pc)
1746 ········{
1747 ············if (pc.NDOObjectState != NDOObjectState.Persistent)
1748 ················return;
1749 ············SaveObjectState(pc);
1750 ············pc.NDOObjectState = NDOObjectState.PersistentDirty;
1751 ········}
1752
1753 ········/// <summary>
1754 ········/// Mark the object dirty, but make sure first, that the object is loaded.
1755 ········/// The current or loaded state is saved in a DataRow, which is stored in the DS.
1756 ········/// This is done, to allow easy rollback later. Also, the
1757 ········/// object is locked in the cache.
1758 ········/// </summary>
1759 ········/// <param name="pc"></param>
1760 ········internal void LoadAndMarkDirty(IPersistenceCapable pc)
1761 ········{
1762 ············Debug.Assert(pc.NDOObjectState != NDOObjectState.Transient, "Transient objects can't be marked as dirty.");
1763
1764 ············if(pc.NDOObjectState == NDOObjectState.Deleted)
1765 ············{
1766 ················throw new NDOException(73, "LoadAndMarkDirty: Access to deleted objects is not allowed.");
1767 ············}
1768
1769 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
1770 ················LoadData(pc);
1771
1772 ············// state is either (Created), Persistent, PersistentDirty
1773 ············if(pc.NDOObjectState == NDOObjectState.Persistent)
1774 ············{
1775 ················MarkDirty(pc);
1776 ············}
1777 ········}
1778
1779
1780
1781 ········/// <summary>
1782 ········/// Save current object state in DS and lock the object in the cache.
1783 ········/// The saved state can be used later to retrieve the original object value if the
1784 ········/// current transaction is aborted. Also the state of all relations (not related objects) is stored.
1785 ········/// </summary>
1786 ········/// <param name="pc">The object that should be saved</param>
1787 ········/// <param name="isDeleting">Determines, if the object is about being deletet.</param>
1788 ········/// <remarks>
1789 ········/// In a data row there are the following things:
1790 ········/// Item································Responsible for writing
1791 ········/// State (own, inherited, embedded)····WriteObject
1792 ········/// TimeStamp····························NDOPersistenceHandler
1793 ········/// Oid····································WriteId
1794 ········/// Foreign Keys and their Type Codes····WriteForeignKeys
1795 ········/// </remarks>
1796 ········protected virtual void SaveObjectState(IPersistenceCapable pc, bool isDeleting = false)
1797 ········{
1798 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Persistent, "Object must be unmodified and persistent but is " + pc.NDOObjectState);
1799 ············
1800 ············DataTable table = GetTable(pc);
1801 ············DataRow row = table.NewRow();
1802 ············Class cl = GetClass(pc);
1803 ············WriteObject(pc, row, cl.ColumnNames, 0);
1804 ············WriteIdToRow(pc, row);
1805 ············if (!isDeleting)
1806 ················WriteLostForeignKeysToRow(cl, pc, row);
1807 ············table.Rows.Add(row);
1808 ············row.AcceptChanges();
1809 ············
1810 ············var relations = CollectRelationStates(pc);
1811 ············cache.Lock(pc, row, relations);
1812 ········}
1813
1814 ········private void SaveFakeRow(IPersistenceCapable pc)
1815 ········{
1816 ············Debug.Assert(pc.NDOObjectState == NDOObjectState.Hollow, "Object must be hollow but is " + pc.NDOObjectState);
1817 ············
1818 ············DataTable table = GetTable(pc);
1819 ············DataRow row = table.NewRow();
1820 ············Class pcClass = GetClass(pc);
1821 ············row.SetColumnError(GetFakeRowOidColumnName(pcClass), hollowMarker);
1822 ············Class cl = GetClass(pc);
1823 ············//WriteObject(pc, row, cl.FieldNames, 0);
1824 ············WriteIdToRow(pc, row);
1825 ············table.Rows.Add(row);
1826 ············row.AcceptChanges();
1827 ············
1828 ············cache.Lock(pc, row, null);
1829 ········}
1830
1831 ········/// <summary>
1832 ········/// This defines one column of the row, in which we use the
1833 ········/// ColumnError property to determine, if the row is a fake row.
1834 ········/// </summary>
1835 ········/// <param name="pcClass"></param>
1836 ········/// <returns></returns>
1837 ········private string GetFakeRowOidColumnName(Class pcClass)
1838 ········{
1839 ············// In case of several OidColumns the first column defined in the mapping
1840 ············// will be the one, holding the fake row info.
1841 ············return ((OidColumn)pcClass.Oid.OidColumns[0]).Name;
1842 ········}
1843
1844 ········private bool IsFakeRow(Class cl, DataRow row)
1845 ········{
1846 ············return (row.GetColumnError(GetFakeRowOidColumnName(cl)) == hollowMarker);
1847 ········}
1848
1849 ········/// <summary>
1850 ········/// Make a list of objects persistent.
1851 ········/// </summary>
1852 ········/// <param name="list">the list of IPersistenceCapable objects</param>
1853 ········public void MakePersistent(System.Collections.IList list)
1854 ········{
1855 ············foreach (IPersistenceCapable pc in list)
1856 ············{
1857 ················MakePersistent(pc);
1858 ············}
1859 ········}
1860
1861 ········/// <summary>
1862 ········/// Save state of related objects in the cache. Only the list itself is duplicated and stored. The related objects are
1863 ········/// not duplicated.
1864 ········/// </summary>
1865 ········/// <param name="pc">the parent object of all relations</param>
1866 ········/// <returns></returns>
1867 ········protected internal virtual List<KeyValuePair<Relation,object>> CollectRelationStates(IPersistenceCapable pc)
1868 ········{
1869 ············// Save state of relations
1870 ············Class c = GetClass(pc);
1871 ············List<KeyValuePair<Relation, object>> relations = new List<KeyValuePair<Relation, object>>( c.Relations.Count());
1872 ············foreach(Relation r in c.Relations)
1873 ············{
1874 ················if (r.Multiplicity == RelationMultiplicity.Element)
1875 ················{
1876 ····················relations.Add( new KeyValuePair<Relation, object>( r, mappings.GetRelationField( pc, r.FieldName ) ) );
1877 ················}
1878 ················else
1879 ················{
1880 ····················IList l = mappings.GetRelationContainer(pc, r);
1881 ····················if(l != null)
1882 ····················{
1883 ························l = (IList) ListCloner.CloneList(l);
1884 ····················}
1885 ····················relations.Add( new KeyValuePair<Relation, object>( r, l ) );
1886 ················}
1887 ············}
1888
1889 ············return relations;
1890 ········}
1891
1892
1893 ········/// <summary>
1894 ········/// Restore the saved relations.··Note that the objects are not restored as this is handled transparently
1895 ········/// by the normal persistence mechanism. Only the number and order of objects are restored, e.g. the state,
1896 ········/// the list had at the beginning of the transaction.
1897 ········/// </summary>
1898 ········/// <param name="pc"></param>
1899 ········/// <param name="relations"></param>
1900 ········private void RestoreRelatedObjects(IPersistenceCapable pc, List<KeyValuePair<Relation, object>> relations )
1901 ········{
1902 ············Class c = GetClass(pc);
1903
1904 ············foreach(var entry in relations)
1905 ············{
1906 ················var r = entry.Key;
1907 ················if (r.Multiplicity == RelationMultiplicity.Element)
1908 ················{
1909 ····················mappings.SetRelationField(pc, r.FieldName, entry.Value);
1910 ················}
1911 ················else
1912 ················{
1913 ····················if (pc.NDOGetLoadState(r.Ordinal))
1914 ····················{
1915 ························// Help GC by clearing lists
1916 ························IList l = mappings.GetRelationContainer(pc, r);
1917 ························if(l != null)
1918 ························{
1919 ····························l.Clear();
1920 ························}
1921 ························// Restore relation
1922 ························mappings.SetRelationContainer(pc, r, (IList)entry.Value);
1923 ····················}
1924 ················}
1925 ············}
1926 ········}
1927
1928
1929 ········/// <summary>
1930 ········/// Generates a query for related objects without mapping table.
1931 ········/// Note: this function can't be called in polymorphic scenarios,
1932 ········/// since they need a mapping table.
1933 ········/// </summary>
1934 ········/// <returns></returns>
1935 ········async Task<IList> QueryRelatedObjectsAsync( IPersistenceCapable pc, Relation r, IList l, bool hollow, CancellationToken cancellationToken )
1936 ········{
1937 ············// At this point of execution we know,
1938 ············// that the target type is not polymorphic and is not 1:1.
1939
1940 ············// We can't fetch these objects with an NDOql query
1941 ············// since this would require a relation in the opposite direction
1942
1943 ············IList relatedObjects;
1944 ············if (l != null)
1945 ················relatedObjects = l;
1946 ············else
1947 ················relatedObjects = mappings.CreateRelationContainer( pc, r );
1948
1949 ············Type t = r.ReferencedType;
1950 ············Class cl = GetClass( t );
1951 ············var provider = cl.Provider;
1952
1953 ············StringBuilder sb = new StringBuilder("SELECT * FROM ");
1954 ············var relClass = GetClass( r.ReferencedType );
1955 ············sb.Append( GetClass( r.ReferencedType ).GetQualifiedTableName() );
1956 ············sb.Append( " WHERE " );
1957 ············int i = 0;
1958 ············List<object> parameters = new List<object>();
1959 ············new ForeignKeyIterator( r ).Iterate( delegate ( ForeignKeyColumn fkColumn, bool isLastElement )
1960 ·············· {
1961 ·················· sb.Append( fkColumn.GetQualifiedName(relClass) );
1962 ·················· sb.Append( " = {" );
1963 ·················· sb.Append(i);
1964 ·················· sb.Append( '}' );
1965 ·················· parameters.Add( pc.NDOObjectId.Id[i] );
1966 ·················· if (!isLastElement)
1967 ······················ sb.Append( " AND " );
1968 ·················· i++;
1969 ·············· } );
1970
1971 ············if (!(String.IsNullOrEmpty( r.ForeignKeyTypeColumnName )))
1972 ············{
1973 ················sb.Append( " AND " );
1974 ················sb.Append( provider.GetQualifiedTableName( relClass.TableName + "." + r.ForeignKeyTypeColumnName ) );
1975 ················sb.Append( " = " );
1976 ················sb.Append( pc.NDOObjectId.Id.TypeId );
1977 ············}
1978
1979 ············IQuery q = NewQuery( t, sb.ToString(), hollow, Query.QueryLanguage.Sql );
1980
1981 ············foreach (var p in parameters)
1982 ············{
1983 ················q.Parameters.Add( p );
1984 ············}
1985
1986 ············q.AllowSubclasses = false;··// Remember: polymorphic relations always have a mapping table
1987
1988 ············IList l2 = await q.ExecuteAsync( cancellationToken ).ConfigureAwait( false );
1989
1990 ············foreach (object o in l2)
1991 ················relatedObjects.Add( o );
1992
1993 ············return relatedObjects;
1994 ········}
1995
1996 ········/// <summary>
1997 ········/// Resolves a relation.
1998 ········/// </summary>
1999 ········/// <typeparam name="T">The type of the parent object</typeparam>
2000 ········/// <param name="parentObject">The parent object</param>
2001 ········/// <param name="expression">An expression like <c>_ => _.Name</c></param>
2002 ········/// <param name="hollow">Determines, if the objects should be hollow. Default Value: false</param>
2003 ········/// <param name="cancellationToken">A Task cancellation token.</param>
2004 ········/// <returns></returns>
2005 ········/// <exception cref="ArgumentNullException"></exception>
2006 ········/// <exception cref="ArgumentException"></exception>
2007 ········public virtual async Task LoadRelationAsync<T>( T parentObject, Expression<Func<T, object>> expression, bool hollow = false, CancellationToken cancellationToken = default )
2008 ········{
2009 ············if (expression == null)
2010 ················throw new ArgumentNullException( nameof( expression ) );
2011
2012 ············Expression body = expression.Body;
2013
2014 ············// If the Property is a ValueType (e.g. int, bool) the Compiler
2015 ············// automatically inserts a 'Convert'-Operation (Boxing). This must be removed
2016 ············if (body is UnaryExpression unaryExpression && unaryExpression.NodeType == ExpressionType.Convert)
2017 ············{
2018 ················body = unaryExpression.Operand;
2019 ············}
2020
2021 ············// Is the expression a property or field?
2022 ············if (body is MemberExpression memberExpression)
2023 ············{
2024 ················var memberName = memberExpression.Member.Name;
2025 ················await LoadRelationAsync( parentObject, memberName, hollow, cancellationToken ).ConfigureAwait( false );
2026 ············}
2027
2028 ············throw new ArgumentException( "Expression must be a property or field." );
2029 ········}
2030
2031 ········/// <summary>
2032 ········/// Resolves an relation. The loaded objects will be hollow.
2033 ········/// </summary>
2034 ········/// <param name="o">The parent object.</param>
2035 ········/// <param name="fieldName">The field name of the container or variable, which represents the relation.</param>
2036 ········/// <param name="hollow">True, if the fetched objects should be hollow.</param>
2037 ········/// <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>
2038 ········public void LoadRelation(object o, string fieldName, bool hollow)
2039 ········{
2040 ············LoadRelationAsync( o, fieldName, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
2041 ········}
2042
2043 ········/// <summary>
2044 ········/// Resolves an relation asynchronously.
2045 ········/// </summary>
2046 ········/// <param name="o">The parent object.</param>
2047 ········/// <param name="fieldName">The field name of the container or variable, which represents the relation.</param>
2048 ········/// <param name="hollow">True, if the fetched objects should be hollow.</param>
2049 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2050 ········/// <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>
2051 ········public virtual async Task LoadRelationAsync( object o, string fieldName, bool hollow, CancellationToken cancellationToken = default )
2052 ········{
2053 ············using (EnterOperation())
2054 ············{
2055 ················IPersistenceCapable pc = CheckPc(o);
2056 ················await LoadRelationInternalAsync( pc, fieldName, hollow, cancellationToken ).ConfigureAwait( false );
2057 ············}
2058 ········}
2059
2060 ········
2061
2062 ········internal IList LoadRelation(IPersistenceCapable pc, Relation r, bool hollow)
2063 ········{
2064 ············return LoadRelationAsync( pc, r, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
2065 ········}
2066
2067 ········internal async Task<IList> LoadRelationAsync( IPersistenceCapable pc, Relation r, bool hollow, CancellationToken cancellationToken = default )
2068 ········{
2069 ············using (EnterOperation())
2070 ············{
2071 ················return await LoadRelationCoreAsync( pc, r, hollow, cancellationToken ).ConfigureAwait( false );
2072 ············}
2073 ········}
2074
2075 ········async Task<IList> LoadRelationCoreAsync( IPersistenceCapable pc, Relation r, bool hollow, CancellationToken cancellationToken )
2076 ········{
2077 ············IList result = null;
2078
2079 ············if (pc.NDOObjectState == NDOObjectState.Created)
2080 ················return null;
2081
2082 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
2083 ················await LoadDataAsync( pc, cancellationToken ).ConfigureAwait( false );
2084
2085 ············if(r.MappingTable == null)
2086 ············{
2087 ················// 1:1 are loaded with LoadData
2088 ················if (r.Multiplicity == RelationMultiplicity.List)
2089 ················{
2090 ····················// Help GC by clearing lists
2091 ····················IList l = mappings.GetRelationContainer(pc, r);
2092 ····················if(l != null)
2093 ························l.Clear();
2094 ····················IList relatedObjects = await QueryRelatedObjectsAsync( pc, r, l, hollow, cancellationToken ).ConfigureAwait( false );
2095 ····················mappings.SetRelationContainer(pc, r, relatedObjects);
2096 ····················result = relatedObjects;
2097 ················}
2098 ············}
2099 ············else
2100 ············{
2101 ················DataTable dt = null;
2102
2103 ················using (IMappingTableHandler handler = PersistenceHandlerManager.GetPersistenceHandler( pc ).GetMappingTableHandler( r ))
2104 ················{
2105 ····················await CheckTransactionAsync( handler, r.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2106 ····················dt = await handler.FindRelatedObjectsAsync( pc.NDOObjectId, this.ds, cancellationToken ).ConfigureAwait( false );
2107 ················}
2108
2109 ················IList relatedObjects;
2110 ················if(r.Multiplicity == RelationMultiplicity.Element)
2111 ····················relatedObjects = GenericListReflector.CreateList(r.ReferencedType, dt.Rows.Count);
2112 ················else
2113 ················{
2114 ····················relatedObjects = mappings.GetRelationContainer(pc, r);
2115 ····················if(relatedObjects != null)
2116 ························relatedObjects.Clear();··// Objects will be reread
2117 ····················else
2118 ························relatedObjects = mappings.CreateRelationContainer(pc, r);
2119 ················}
2120 ····················
2121 ················foreach(DataRow objRow in dt.Rows)
2122 ················{
2123 ····················Type relType;
2124
2125 ····················if (r.MappingTable.ChildForeignKeyTypeColumnName != null)························
2126 ····················{
2127 ························object typeCodeObj = objRow[r.MappingTable.ChildForeignKeyTypeColumnName];
2128 ························if (typeCodeObj is System.DBNull)
2129 ····························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() ) );
2130 ························relType = typeManager[(int)typeCodeObj];
2131 ························if (relType == null)
2132 ····························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));
2133 ····················}························
2134 ····················else
2135 ····················{
2136 ························relType = r.ReferencedType;
2137 ····················}
2138
2139 ····················//TODO: Generic Types: Exctract the type description from the type name column
2140 ····················if (relType.IsGenericTypeDefinition)
2141 ························throw new NotImplementedException("NDO doesn't support relations to generic types via mapping tables.");
2142 ····················ObjectId id = ObjectIdFactory.NewObjectId(relType, GetClass(relType), objRow, r.MappingTable, this.typeManager);
2143 ····················IPersistenceCapable relObj = FindObject(id);
2144 ····················relatedObjects.Add(relObj);
2145 ················}····
2146 ················if (r.Multiplicity == RelationMultiplicity.Element)
2147 ················{
2148 ····················Debug.Assert(relatedObjects.Count <= 1, "NDO retrieved more than one object for relation with cardinality 1");
2149 ····················mappings.SetRelationField(pc, r.FieldName, relatedObjects.Count > 0 ? relatedObjects[0] : null);
2150 ················}
2151 ················else
2152 ················{
2153 ····················mappings.SetRelationContainer(pc, r, relatedObjects);
2154 ····················result = relatedObjects;
2155 ················}
2156 ············}
2157 ············// Mark relation as loaded
2158 ············pc.NDOSetLoadState(r.Ordinal, true);
2159 ············return result;
2160 ········}
2161
2162 ········/// <summary>
2163 ········/// Loads elements of a relation
2164 ········/// </summary>
2165 ········/// <param name="pc">The object which needs to load the relation</param>
2166 ········/// <param name="relationName">The name of the relation</param>
2167 ········/// <param name="hollow">Determines, if the related objects should be hollow.</param>
2168 ········internal IList LoadRelationInternal(IPersistenceCapable pc, string relationName, bool hollow)
2169 ········{
2170 ············return LoadRelationInternalAsync( pc, relationName, hollow ).ConfigureAwait( false ).GetAwaiter().GetResult();
2171 ········}
2172
2173 ········internal async Task<IList> LoadRelationInternalAsync( IPersistenceCapable pc, string relationName, bool hollow, CancellationToken cancellationToken = default )
2174 ········{
2175 ············if (pc.NDOObjectState == NDOObjectState.Created)
2176 ················return null;
2177 ············Class cl = GetClass(pc);
2178
2179 ············Relation r = cl.FindRelation(relationName);
2180
2181 ············if ( r == null )
2182 ················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 ) );
2183
2184 ············if ( pc.NDOGetLoadState( r.Ordinal ) )
2185 ················return null;
2186
2187 ············return await LoadRelationAsync( pc, r, hollow, cancellationToken ).ConfigureAwait( false );
2188 ········}
2189
2190 ········/// <summary>
2191 ········/// Load the related objects of a parent object. The current value of the relation is replaced by the
2192 ········/// a list of objects that has been read from the DB.
2193 ········/// </summary>
2194 ········/// <param name="pc">The parent object of the relations</param>
2195 ········/// <param name="row">A data row containing the state of the object</param>
2196 ········private void LoadRelated1To1Objects(IPersistenceCapable pc, DataRow row)
2197 ········{
2198 ············// Stripped down to only serve 1:1-Relations w/out mapping table
2199 ············Class cl = GetClass(pc);
2200 ············foreach(Relation r in cl.Relations)
2201 ············{
2202 ················if(r.MappingTable == null)
2203 ················{
2204 ····················if (r.Multiplicity == RelationMultiplicity.Element)
2205 ····················{
2206 ························bool isNull = false;
2207 ························foreach (ForeignKeyColumn fkColumn in r.ForeignKeyColumns)
2208 ························{
2209 ····························isNull = isNull || (row[fkColumn.Name] == DBNull.Value);
2210 ························}
2211 ························if (isNull)
2212 ························{
2213 ····························mappings.SetRelationField(pc, r.FieldName, null);
2214 ························}
2215 ························else
2216 ························{
2217 ····························Type relType;
2218 ····························if (r.HasSubclasses)
2219 ····························{
2220 ································object o = row[r.ForeignKeyTypeColumnName];
2221 ································if (o == DBNull.Value)
2222 ····································throw new NDOException(75, String.Format(
2223 ········································"Can't resolve subclass type code {0} of type {1} - type code value is DBNull.",
2224 ········································row[r.ForeignKeyTypeColumnName], r.ReferencedTypeName));
2225 ································relType = typeManager[(int)o];
2226 ····························}
2227 ····························else
2228 ····························{
2229 ································relType = r.ReferencedType;
2230 ····························}
2231 ····························if (relType == null)
2232 ····························{
2233 ································throw new NDOException(75, String.Format(
2234 ····································"Can't resolve subclass type code {0} of type {1} - check, if your mapping file is correct.",
2235 ····································row[r.ForeignKeyTypeColumnName], r.ReferencedTypeName));
2236 ····························}
2237 ····
2238 ····························int count = r.ForeignKeyColumns.Count();
2239 ····························object[] keydata = new object[count];
2240 ····························int i = 0;
2241 ····························foreach(ForeignKeyColumn fkColumn in r.ForeignKeyColumns)
2242 ····························{
2243 ································keydata[i++] = row[fkColumn.Name];
2244 ····························}
2245
2246 ····························Type oidType = relType;
2247 ····························if (oidType.IsGenericTypeDefinition)
2248 ································oidType = mappings.GetRelationFieldType(r);
2249
2250 ····························ObjectId childOid = ObjectIdFactory.NewObjectId(oidType, GetClass(relType), keydata, this.typeManager);
2251 ····························if(childOid.IsValid())
2252 ································mappings.SetRelationField(pc, r.FieldName, FindObject(childOid));
2253 ····························else
2254 ································mappings.SetRelationField(pc, r.FieldName, null);
2255
2256 ························}
2257 ························pc.NDOSetLoadState(r.Ordinal, true);
2258 ····················}
2259 ················}
2260 ············}
2261 ········}
2262
2263 ········
2264 ········/// <summary>
2265 ········/// Creates a new ObjectId with the same Key value as a given ObjectId.
2266 ········/// </summary>
2267 ········/// <param name="oid">An ObjectId, which Key value will be used to build the new ObjectId.</param>
2268 ········/// <param name="t">The type of the object, the id will belong to.</param>
2269 ········/// <returns>An object of type ObjectId, or ObjectId.InvalidId</returns>
2270 ········/// <remarks>If the type t doesn't have a mapping in the mapping file an Exception of type NDOException is thrown.</remarks>
2271 ········public ObjectId NewObjectId(ObjectId oid, Type t)
2272 ········{
2273 ············return new ObjectId(oid.Id, t);
2274 ········}
2275
2276 ········/*
2277 ········/// <summary>
2278 ········/// Creates a new ObjectId which can be used to retrieve objects from the database.
2279 ········/// </summary>
2280 ········/// <param name="keyData">The id, which will be used to search for the object in the database</param>
2281 ········/// <param name="t">The type of the object.</param>
2282 ········/// <returns>An object of type ObjectId, or ObjectId.InvalidId</returns>
2283 ········/// <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>
2284 ········public ObjectId NewObjectId(object keyData, Type t)
2285 ········{
2286 ············if (keyData == null || keyData == DBNull.Value)
2287 ················return ObjectId.InvalidId;
2288
2289 ············Class cl =··GetClass(t);············
2290 ············
2291 ············if (cl.Oid.FieldType == typeof(int))
2292 ················return new ObjectId(new Int32Key(t, (int)keyData));
2293 ············else if (cl.Oid.FieldType == typeof(string))
2294 ················return new ObjectId(new StringKey(t, (String) keyData));
2295 ············else if (cl.Oid.FieldType == typeof(Guid))
2296 ················if (keyData is string)
2297 ····················return new ObjectId(new GuidKey(t, new Guid((String) keyData)));
2298 ················else
2299 ····················return new ObjectId(new GuidKey(t, (Guid) keyData));
2300 ············else if (cl.Oid.FieldType == typeof(MultiKey))
2301 ················return new ObjectId(new MultiKey(t, (object[]) keyData));
2302 ············else
2303 ················return ObjectId.InvalidId;
2304 ········}
2305 ········*/
2306
2307
2308 ········/*
2309 ········ * ····················if (cl.Oid.FieldName != null && HasOwnerCreatedIds)
2310 ····················{
2311 ························// The column, which hold the oid gets overwritten, if
2312 ························// Oid.FieldName contains a value.
2313 */
2314 ········private void WriteIdFieldsToRow(IPersistenceCapable pc, DataRow row)
2315 ········{
2316 ············Class cl = GetClass(pc);
2317
2318 ············if (cl.Oid.IsDependent)
2319 ················return;
2320
2321 ············Key key = pc.NDOObjectId.Id;
2322
2323 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2324 ············{
2325 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2326 ················if (oidColumn.FieldName != null)
2327 ················{
2328 ····················row[oidColumn.Name] = key[i];
2329 ················}
2330 ············}
2331 ········}
2332
2333 ········private void WriteIdToRow(IPersistenceCapable pc, DataRow row)
2334 ········{
2335 ············NDO.Mapping.Class cl = GetClass(pc);
2336 ············ObjectId oid = pc.NDOObjectId;
2337
2338 ············if (cl.TimeStampColumn != null)
2339 ················row[cl.TimeStampColumn] = pc.NDOTimeStamp;
2340
2341 ············if (cl.Oid.IsDependent)··// Oid data is in relation columns
2342 ················return;
2343
2344 ············Key key = oid.Id;
2345
2346 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2347 ············{
2348 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2349 ················row[oidColumn.Name] = key[i];
2350 ············}
2351 ········}
2352
2353 ········private void ReadIdFromRow(IPersistenceCapable pc, DataRow row)
2354 ········{
2355 ············ObjectId oid = pc.NDOObjectId;
2356 ············NDO.Mapping.Class cl = GetClass(pc);
2357
2358 ············if (cl.Oid.IsDependent)··// Oid data is in relation columns
2359 ················return;
2360
2361 ············Key key = oid.Id;
2362
2363 ············for (int i = 0; i < cl.Oid.OidColumns.Count; i++)
2364 ············{
2365 ················OidColumn oidColumn = (OidColumn)cl.Oid.OidColumns[i];
2366 ················object o = row[oidColumn.Name];
2367 ················if (!(o is Int32) && !(o is Guid) && !(o is String) && !(o is Int64))
2368 ····················throw new NDOException(78, "ReadId: invalid Id Column type in " + oidColumn.Name + ": " + o.GetType().FullName);
2369 ················if (oidColumn.SystemType == typeof(Guid) && (o is String))
2370 ····················key[i] = new Guid((string)o);
2371 ················else
2372 ····················key[i] = o;
2373 ············}
2374
2375 ········}
2376
2377 ········private void ReadId (Cache.Entry e)
2378 ········{
2379 ············ReadIdFromRow(e.pc, e.row);
2380 ········}
2381
2382 ········private void WriteObject(IPersistenceCapable pc, DataRow row, string[] fieldNames)
2383 ········{
2384 ············WriteObject(pc, row, fieldNames, 0);
2385 ········}
2386
2387 ········private void ReadTimeStamp(Class cl, IPersistenceCapable pc, DataRow row)
2388 ········{
2389 ············if (cl.TimeStampColumn == null)
2390 ················return;
2391 ············object col = row[cl.TimeStampColumn];
2392 ············if (col is String)
2393 ················pc.NDOTimeStamp = new Guid(col.ToString());
2394 ············else
2395 ················pc.NDOTimeStamp = (Guid) col;
2396 ········}
2397
2398
2399
2400 ········private void ReadTimeStamp(Cache.Entry e)
2401 ········{
2402 ············IPersistenceCapable pc = e.pc;
2403 ············NDO.Mapping.Class cl = GetClass(pc);
2404 ············Debug.Assert(!IsFakeRow(cl, e.row));
2405 ············if (cl.TimeStampColumn == null)
2406 ················return;
2407 ············if (e.row[cl.TimeStampColumn] is String)
2408 ················e.pc.NDOTimeStamp = new Guid(e.row[cl.TimeStampColumn].ToString());
2409 ············else
2410 ················e.pc.NDOTimeStamp = (Guid) e.row[cl.TimeStampColumn];
2411 ········}
2412
2413 ········/// <summary>
2414 ········/// Determines, if any objects are new, changed or deleted.
2415 ········/// </summary>
2416 ········public virtual bool HasChanges
2417 ········{
2418 ············get
2419 ············{
2420 ················return cache.LockedObjects.Count > 0;
2421 ············}
2422 ········}
2423
2424 ········/// <summary>
2425 ········/// Do the update for all rows in the ds.
2426 ········/// </summary>
2427 ········/// <param name="types">Types with changes.</param>
2428 ········/// <param name="delete">True, if delete operations are to be performed.</param>
2429 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2430 ········/// <remarks>
2431 ········/// Delete and Insert/Update operations are to be separated to maintain the type order.
2432 ········/// </remarks>
2433 ········private async Task UpdateTypesAsync( IList types, bool delete, CancellationToken cancellationToken )
2434 ········{
2435 ············foreach(Type t in types)
2436 ············{
2437 ················//Debug.WriteLine("Update Deleted Objects: "··+ t.Name);
2438 ················using (IPersistenceHandler handler = PersistenceHandlerManager.GetPersistenceHandler( t ))
2439 ················{
2440 ····················await CheckTransactionAsync( handler, t, cancellationToken ).ConfigureAwait( false );
2441 ····················ConcurrencyErrorHandler ceh = new ConcurrencyErrorHandler(this.OnConcurrencyError);
2442 ····················handler.ConcurrencyError += ceh;
2443 ····················try
2444 ····················{
2445 ························DataTable dt = GetTable(t);
2446 ························if (delete)
2447 ····························await handler.UpdateDeletedObjectsAsync( dt, cancellationToken ).ConfigureAwait( false );
2448 ························else
2449 ····························await handler.UpdateAsync( dt, cancellationToken ).ConfigureAwait( false );
2450 ····················}
2451 ····················finally
2452 ····················{
2453 ························handler.ConcurrencyError -= ceh;
2454 ····················}
2455 ················}
2456 ············}
2457 ········}
2458
2459 ········internal async Task UpdateCreatedMappingTableEntriesAsync( CancellationToken cancellationToken )
2460 ········{
2461 ············foreach (MappingTableEntry e in createdMappingTableObjects)
2462 ············{
2463 ················if (!e.DeleteEntry)
2464 ····················WriteMappingTableEntry(e);
2465 ············}
2466 ············// Now update all mapping tables
2467 ············foreach (IMappingTableHandler handler in mappingHandler.Values)
2468 ············{
2469 ················await CheckTransactionAsync( handler, handler.Relation.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2470 ················await handler.UpdateAsync( ds, cancellationToken ).ConfigureAwait( false );
2471 ············}
2472 ········}
2473
2474 ········internal async Task UpdateDeletedMappingTableEntriesAsync( CancellationToken cancellationToken )
2475 ········{
2476 ············foreach (MappingTableEntry e in createdMappingTableObjects)
2477 ············{
2478 ················if (e.DeleteEntry)
2479 ····················WriteMappingTableEntry(e);
2480 ············}
2481 ············// Now update all mapping tables
2482 ············foreach (IMappingTableHandler handler in mappingHandler.Values)
2483 ············{
2484 ················await CheckTransactionAsync( handler, handler.Relation.MappingTable.Connection, cancellationToken ).ConfigureAwait( false );
2485 ················await handler.UpdateAsync( ds, cancellationToken ).ConfigureAwait( false );
2486 ············}
2487 ········}
2488
2489 ········/// <summary>
2490 ········/// Save all changed object into the DataSet and update the DB.
2491 ········/// When a newly created object is written to DB, the key might change. Therefore,
2492 ········/// the id is updated and the object is removed and re-inserted into the cache.
2493 ········/// </summary>
2494 ········public void Save(bool deferCommit = false)
2495 ········{
2496 ············SaveAsync( deferCommit ).ConfigureAwait( false ).GetAwaiter().GetResult();
2497 ········}
2498
2499 ········/// <summary>
2500 ········/// Save all changed object into the DataSet and update the DB asynchronously.
2501 ········/// When a newly created object is written to DB, the key might change. Therefore,
2502 ········/// the id is updated and the object is removed and re-inserted into the cache.
2503 ········/// </summary>
2504 ········/// <param name="deferCommit">Determines, if the commit of the transaction should be deferred.</param>
2505 ········/// <param name="cancellationToken">A token to cancel the operation</param>
2506 ········/// <remarks>
2507 ········/// User callbacks like CollisionEvent and OnSavedEvent might be called on a thread pool thread.
2508 ········/// </remarks>
2509 ········public virtual async Task SaveAsync( bool deferCommit = false, CancellationToken cancellationToken = default )
2510 ········{
2511 ············using (EnterOperation())
2512 ············{
2513 ················await SaveInternalAsync( deferCommit, cancellationToken ).ConfigureAwait( false );
2514 ············}
2515 ········}
2516
2517 ········async Task SaveInternalAsync( bool deferCommit, CancellationToken cancellationToken )
2518 ········{
2519 ············if (IsClosed)
2520 ················throw new ObjectDisposedException(GetType().Name);
2521
2522 ············this.DeferredMode = deferCommit;
2523 ············var htOnSaving = new HashSet<ObjectId>();
2524 ············for(;;)
2525 ············{
2526 ················// We need to work on a copy of the locked objects list,
2527 ················// since the handlers might add more objects to the cache
2528 ················var lockedObjects = cache.LockedObjects.ToList();
2529 ················int count = lockedObjects.Count;
2530 ················foreach(Cache.Entry e in lockedObjects)
2531 ················{
2532 ····················if (e.pc.NDOObjectState != NDOObjectState.Deleted)
2533 ····················{
2534 ························IPersistenceNotifiable ipn = e.pc as IPersistenceNotifiable;
2535 ························if (ipn != null)
2536 ························{
2537 ····························if (!htOnSaving.Contains(e.pc.NDOObjectId))
2538 ····························{
2539 ································ipn.OnSaving();
2540 ································htOnSaving.Add(e.pc.NDOObjectId);
2541 ····························}
2542 ························}
2543 ····················}
2544 ················}
2545 ················// The system is stable, if the count doesn't change
2546 ················if (cache.LockedObjects.Count == count)
2547 ····················break;
2548 ············}
2549
2550 ············if (this.OnSavingEvent != null)
2551 ············{
2552 ················IList onSavingObjects = new ArrayList(cache.LockedObjects.Count);
2553 ················foreach(Cache.Entry e in cache.LockedObjects)
2554 ····················onSavingObjects.Add(e.pc);
2555 ················OnSavingEvent(onSavingObjects);
2556 ············}
2557
2558 ············List<Type> types = new List<Type>();
2559 ············List<IPersistenceCapable> deletedObjects = new List<IPersistenceCapable>();
2560 ············List<IPersistenceCapable> hollowModeObjects = hollowMode ? new List<IPersistenceCapable>() : null;
2561 ············List<IPersistenceCapable> changedObjects = new List<IPersistenceCapable>();
2562 ············List<IPersistenceCapable> addedObjects = new List<IPersistenceCapable>();
2563 ············List<Cache.Entry> addedCacheEntries = new List<Cache.Entry>();
2564
2565 ············// Save current state in DataSet
2566 ············foreach (Cache.Entry e in cache.LockedObjects)
2567 ············{
2568 ················Type objType = e.pc.GetType();
2569
2570 ················if (objType.IsGenericType && !objType.IsGenericTypeDefinition)
2571 ····················objType = objType.GetGenericTypeDefinition();
2572
2573 ················Class cl = GetClass(e.pc);
2574 ················//Debug.WriteLine("Saving: " + objType.Name + " id = " + e.pc.NDOObjectId.Dump());
2575 ················if(!types.Contains(objType))
2576 ················{
2577 ····················//Debug.WriteLine("Added··type " + objType.Name);
2578 ····················types.Add(objType);
2579 ················}
2580 ················NDOObjectState objectState = e.pc.NDOObjectState;
2581 ················if(objectState == NDOObjectState.Deleted)
2582 ················{
2583 ····················deletedObjects.Add(e.pc);
2584 ················}
2585 ················else if(objectState == NDOObjectState.Created)
2586 ················{
2587 ····················WriteObject(e.pc, e.row, cl.ColumnNames);····················
2588 ····················WriteIdFieldsToRow(e.pc, e.row);··// If fields are mapped to Oid, write them into the row
2589 ····················WriteForeignKeysToRow(e.pc, e.row);
2590 ····················//····················Debug.WriteLine(e.pc.GetType().FullName);
2591 ····················//····················DataRow[] rows = new DataRow[cache.LockedObjects.Count];
2592 ····················//····················i = 0;
2593 ····················//····················foreach(Cache.Entry e2 in cache.LockedObjects)
2594 ····················//····················{
2595 ····················//························rows[i++] = e2.row;
2596 ····················//····················}
2597 ····················//····················System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("testCommand");
2598 ····················//····················new SqlDumper(new DebugLogAdapter(), NDOProviderFactory.Instance["Sql"], cmd, cmd, cmd, cmd).Dump(rows);
2599
2600 ····················addedCacheEntries.Add(e);
2601 ····················addedObjects.Add( e.pc );
2602 ····················//····················objectState = NDOObjectState.Persistent;
2603 ················}
2604 ················else
2605 ················{
2606 ····················if (e.pc.NDOObjectState == NDOObjectState.PersistentDirty)
2607 ························changedObjects.Add( e.pc );
2608 ····················WriteObject(e.pc, e.row, cl.ColumnNames);
2609 ····················WriteForeignKeysToRow(e.pc, e.row); ····················
2610 ················}
2611 ················if(hollowMode && (objectState == NDOObjectState.Persistent || objectState == NDOObjectState.Created || objectState == NDOObjectState.PersistentDirty) )
2612 ················{
2613 ····················hollowModeObjects.Add(e.pc);
2614 ················}
2615 ············}
2616
2617 ············// Before we delete any db rows, we have to make sure, to delete mapping
2618 ············// table entries first, which might have relations to the db rows to be deleted
2619 ············await UpdateDeletedMappingTableEntriesAsync( cancellationToken ).ConfigureAwait( false );
2620
2621 ············// Update DB
2622 ············if (ds.HasChanges())
2623 ············{
2624
2625 ················// We need the reversed update order for deletions.
2626 ················types.Sort( ( t1, t2 ) =>
2627 ················{
2628 ····················int i1 = mappings.GetUpdateOrder( t1 );
2629 ····················int i2 = mappings.GetUpdateOrder( t2 );
2630 ····················if (i1 < i2)
2631 ····················{
2632 ························if (!addedObjects.Any( pc => pc.GetType() == t1 ))
2633 ····························i1 += 100000;
2634 ····················}
2635 ····················else
2636 ····················{
2637 ························if (!addedObjects.Any( pc => pc.GetType() == t2 ))
2638 ····························i2 += 100000;
2639 ····················}
2640 ····················return i2 - i1;
2641 ················} );
2642
2643 ················// Delete records first
2644
2645 ················await UpdateTypesAsync( types, true, cancellationToken ).ConfigureAwait( false );
2646
2647 ················// Now do all other updates in correct order.
2648 ················types.Reverse();
2649
2650 ················await UpdateTypesAsync( types, false, cancellationToken ).ConfigureAwait( false );
2651 ················
2652 ················ds.AcceptChanges();
2653 ················if(createdDirectObjects.Count > 0)
2654 ················{
2655 ····················// Rewrite all children that have foreign keys to parents which have just been saved now.
2656 ····················// They must be written again to store the correct foreign keys.
2657 ····················foreach(IPersistenceCapable pc in createdDirectObjects)
2658 ····················{
2659 ························Class cl = GetClass(pc);
2660 ························DataRow r = this.cache.GetDataRow(pc);
2661 ························string fakeColumnName = GetFakeRowOidColumnName(cl);
2662 ························object o = r[fakeColumnName];
2663 ························r[fakeColumnName] = o;
2664 ····················}
2665
2666 ····················await UpdateTypesAsync( types, false, cancellationToken ).ConfigureAwait( false );
2667 ················}
2668
2669 ················// Because object id might have changed during DB insertion, re-register newly created objects in the cache.
2670 ················foreach(Cache.Entry e in addedCacheEntries)
2671 ················{
2672 ····················cache.DeregisterLockedObject(e.pc);
2673 ····················ReadId(e);
2674 ····················cache.RegisterLockedObject(e.pc, e.row, e.relations);
2675 ················}
2676
2677 ················// Now update all mapping tables. Because of possible subclasses, there is no
2678 ················// relation between keys in the dataset schema. Therefore, we can update mapping
2679 ················// tables only after all other objects have been written to ensure correct foreign keys.
2680 ················await UpdateCreatedMappingTableEntriesAsync( cancellationToken ).ConfigureAwait( false );
2681
2682 ················// The rows may contain now new Ids, which should be
2683 ················// stored in the lostRowInfo's before the rows get detached
2684 ················foreach(Cache.Entry e in cache.LockedObjects)
2685 ················{
2686 ····················if (e.row.RowState != DataRowState.Detached)
2687 ····················{
2688 ························IPersistenceCapable pc = e.pc;
2689 ························ReadLostForeignKeysFromRow(GetClass(pc), pc, e.row);
2690 ····················}
2691 ················}
2692
2693 ················ds.AcceptChanges();
2694 ············}
2695
2696 ············await EndSaveAsync( !deferCommit, cancellationToken ).ConfigureAwait( false );
2697
2698 ············foreach(IPersistenceCapable pc in deletedObjects)
2699 ············{
2700 ················MakeObjectTransient(pc, false);
2701 ············}
2702
2703 ············ds.Clear();
2704 ············mappingHandler.Clear();
2705 ············createdDirectObjects.Clear();
2706 ············createdMappingTableObjects.Clear();
2707 ············this.relationChanges.Clear();
2708
2709 ············if(hollowMode)
2710 ············{
2711 ················MakeHollow(hollowModeObjects);
2712 ············}
2713
2714 ············if (this.OnSavedEvent != null)
2715 ············{
2716 ················AuditSet auditSet = new AuditSet()
2717 ················{
2718 ····················ChangedObjects = changedObjects,
2719 ····················CreatedObjects = addedObjects,
2720 ····················DeletedObjects = deletedObjects
2721 ················};
2722 ················this.OnSavedEvent( auditSet );
2723 ············}
2724 ········}
2725
2726 ········private async Task EndSaveAsync( bool forceCommit, CancellationToken cancellationToken )
2727 ········{
2728 ············foreach(Cache.Entry e in cache.LockedObjects)
2729 ············{
2730 ················if (e.pc.NDOObjectState == NDOObjectState.Created || e.pc.NDOObjectState == NDOObjectState.PersistentDirty)
2731 ····················this.ReadTimeStamp(e);
2732 ················e.pc.NDOObjectState = NDOObjectState.Persistent;
2733 ············}
2734
2735 ············cache.UnlockAll();
2736
2737 ············await CheckEndTransactionAsync( forceCommit, cancellationToken ).ConfigureAwait( false );
2738 ········}
2739
2740 ········/// <summary>
2741 ········/// Write all foreign keys for 1:1-relations.
2742 ········/// </summary>
2743 ········/// <param name="pc">The persistent object.</param>
2744 ········/// <param name="pcRow">The DataRow of the pesistent object.</param>
2745 ········private void WriteForeignKeysToRow(IPersistenceCapable pc, DataRow pcRow)
2746 ········{
2747 ············foreach(Relation r in mappings.Get1to1Relations(pc.GetType()))
2748 ············{
2749 ················IPersistenceCapable relObj = (IPersistenceCapable)mappings.GetRelationField(pc, r.FieldName);
2750 ················bool isDependent = GetClass(pc).Oid.IsDependent;
2751
2752 ················if ( relObj != null )
2753 ················{
2754 ····················int i = 0;
2755 ····················foreach ( ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2756 ····················{
2757 ························pcRow[fkColumn.Name] = relObj.NDOObjectId.Id[i++];
2758 ····················}
2759 ····················if ( r.ForeignKeyTypeColumnName != null )
2760 ····················{
2761 ························pcRow[r.ForeignKeyTypeColumnName] = relObj.NDOObjectId.Id.TypeId;
2762 ····················}
2763 ················}
2764 ················else
2765 ················{
2766 ····················foreach ( ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2767 ····················{
2768 ························pcRow[fkColumn.Name] = DBNull.Value;
2769 ····················}
2770 ····················if ( r.ForeignKeyTypeColumnName != null )
2771 ····················{
2772 ························pcRow[r.ForeignKeyTypeColumnName] = DBNull.Value;
2773 ····················}
2774 ················}
2775 ············}
2776 ········}
2777
2778
2779
2780 ········/// <summary>
2781 ········/// Write a mapping table entry to it's corresponding table. This is a pair of foreign keys.
2782 ········/// </summary>
2783 ········/// <param name="e">the mapping table entry</param>
2784 ········private void WriteMappingTableEntry(MappingTableEntry e)
2785 ········{
2786 ············IPersistenceCapable pc = e.ParentObject;
2787 ············IPersistenceCapable relObj = e.RelatedObject;
2788 ············Relation r = e.Relation;
2789 ············DataTable dt = GetTable(r.MappingTable.TableName);
2790 ············DataRow row = dt.NewRow();
2791 ············int i = 0;
2792 ············foreach (ForeignKeyColumn fkColumn in r.ForeignKeyColumns )
2793 ············{
2794 ················row[fkColumn.Name] = pc.NDOObjectId.Id[i++];
2795 ············}
2796 ············i = 0;
2797 ············foreach (ForeignKeyColumn fkColumn in r.MappingTable.ChildForeignKeyColumns)
2798 ············{
2799 ················row[fkColumn.Name] = relObj.NDOObjectId.Id[i++];
2800 ············}
2801
2802 ············if (r.ForeignKeyTypeColumnName != null)
2803 ················row[r.ForeignKeyTypeColumnName] = pc.NDOObjectId.Id.TypeId;
2804 ············if (r.MappingTable.ChildForeignKeyTypeColumnName != null)
2805 ················row[r.MappingTable.ChildForeignKeyTypeColumnName] = relObj.NDOObjectId.Id.TypeId;
2806
2807 ············dt.Rows.Add(row);
2808 ············if(e.DeleteEntry)
2809 ············{
2810 ················row.AcceptChanges();
2811 ················row.Delete();
2812 ············}
2813
2814 ············IMappingTableHandler handler;
2815 ············if (!mappingHandler.TryGetValue( r, out handler ))
2816 ············{
2817 ················mappingHandler[r] = handler = PersistenceHandlerManager.GetPersistenceHandler( pc ).GetMappingTableHandler( r );
2818 ············}
2819 ········}
2820
2821
2822 ········/// <summary>
2823 ········/// Undo changes of a certain object
2824 ········/// </summary>
2825 ········/// <param name="o">Object to undo</param>
2826 ········public void Restore(object o)
2827 ········{············
2828 ············IPersistenceCapable pc = CheckPc(o);
2829 ············Cache.Entry e = null;
2830 ············foreach (Cache.Entry entry in cache.LockedObjects)
2831 ············{
2832 ················if (entry.pc == pc)
2833 ················{
2834 ····················e = entry;
2835 ····················break;
2836 ················}
2837 ············}
2838 ············if (e == null)
2839 ················return;
2840 ············Class cl = GetClass(e.pc);
2841 ············switch (pc.NDOObjectState)
2842 ············{
2843 ················case NDOObjectState.PersistentDirty:
2844 ····················ObjectListManipulator.Remove(createdDirectObjects, pc);
2845 ····················foreach(Relation r in cl.Relations)
2846 ····················{
2847 ························if (r.Multiplicity == RelationMultiplicity.Element)
2848 ························{
2849 ····························IPersistenceCapable subPc = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
2850 ····························if (subPc != null && cache.IsLocked(subPc))
2851 ································Restore(subPc);
2852 ························}
2853 ························else
2854 ························{
2855 ····························if (!pc.NDOGetLoadState(r.Ordinal))
2856 ································continue;
2857 ····························IList subList = (IList) mappings.GetRelationContainer(pc, r);
2858 ····························if (subList != null)
2859 ····························{
2860 ································foreach(IPersistenceCapable subPc2 in subList)
2861 ································{
2862 ····································if (cache.IsLocked(subPc2))
2863 ········································Restore(subPc2);
2864 ································}
2865 ····························}
2866 ························}
2867 ····················}
2868 ····················RestoreRelatedObjects(pc, e.relations);
2869 ····················e.row.RejectChanges();
2870 ····················ReadObject(pc, e.row, cl.ColumnNames, 0);
2871 ····················cache.Unlock(pc);
2872 ····················pc.NDOObjectState = NDOObjectState.Persistent;
2873 ····················break;
2874 ················case NDOObjectState.Created:
2875 ····················ReadObject(pc, e.row, cl.ColumnNames, 0);
2876 ····················cache.Unlock(pc);
2877 ····················MakeObjectTransient(pc, true);
2878 ····················break;
2879 ················case NDOObjectState.Deleted:
2880 ····················if (!this.IsFakeRow(cl, e.row))
2881 ····················{
2882 ························e.row.RejectChanges();
2883 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2884 ························e.pc.NDOObjectState = NDOObjectState.Persistent;
2885 ····················}
2886 ····················else
2887 ····················{
2888 ························e.row.RejectChanges();
2889 ························e.pc.NDOObjectState = NDOObjectState.Hollow;
2890 ····················}
2891 ····················cache.Unlock(pc);
2892 ····················break;
2893
2894 ············}
2895 ········}
2896
2897 ········/// <summary>
2898 ········/// Aborts a pending transaction without restoring the object state.
2899 ········/// </summary>
2900 ········/// <remarks>Supports both local and EnterpriseService Transactions.</remarks>
2901 ········public void AbortTransaction()
2902 ········{
2903 ············AbortTransactionAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
2904 ········}
2905
2906 ········/// <summary>
2907 ········/// Aborts a pending transaction asynchronously without restoring the object state.
2908 ········/// </summary>
2909 ········/// <remarks>The rollback can't be canceled, therefore there is no CancellationToken.</remarks>
2910 ········public virtual async Task AbortTransactionAsync()
2911 ········{
2912 ············await TransactionScope.DisposeAsync().ConfigureAwait( false );
2913 ········}
2914
2915 ········/// <summary>
2916 ········/// Rejects all changes and restores the original object state. Added Objects will be made transient.
2917 ········/// </summary>
2918 ········public void Abort()
2919 ········{
2920 ············AbortAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
2921 ········}
2922
2923 ········/// <summary>
2924 ········/// Rejects all changes and restores the original object state asynchronously. Added Objects will be made transient.
2925 ········/// </summary>
2926 ········/// <remarks>The rollback can't be canceled, therefore there is no CancellationToken.</remarks>
2927 ········public virtual async Task AbortAsync()
2928 ········{
2929 ············// RejectChanges of the DS cannot be called because newly added rows would be deleted,
2930 ············// and therefore, couldn't be restored. Instead we call RejectChanges() for each
2931 ············// individual row.
2932 ············createdDirectObjects.Clear();
2933 ············createdMappingTableObjects.Clear();
2934 ············ArrayList deletedObjects = new ArrayList();
2935 ············ArrayList hollowModeObjects = hollowMode ? new ArrayList() : null;
2936
2937 ············// Read all objects from DataSet
2938 ············foreach (Cache.Entry e in cache.LockedObjects)
2939 ············{
2940 ················//Debug.WriteLine("Reading: " + e.pc.GetType().Name);
2941
2942 ················Class cl = GetClass(e.pc);
2943 ················bool isFakeRow = this.IsFakeRow(cl, e.row);
2944 ················if (!isFakeRow)
2945 ················{
2946 ····················RestoreRelatedObjects(e.pc, e.relations);
2947 ················}
2948 ················else
2949 ················{
2950 ····················Debug.Assert(e.pc.NDOObjectState == NDOObjectState.Deleted, "Fake row objects can only exist in deleted state");
2951 ················}
2952
2953 ················switch(e.pc.NDOObjectState)
2954 ················{
2955 ····················case NDOObjectState.Created:
2956 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2957 ························deletedObjects.Add(e.pc);
2958 ························break;
2959
2960 ····················case NDOObjectState.PersistentDirty:
2961 ························e.row.RejectChanges();
2962 ························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2963 ························e.pc.NDOObjectState = NDOObjectState.Persistent;
2964 ························break;
2965
2966 ····················case NDOObjectState.Deleted:
2967 ························if (!isFakeRow)
2968 ························{
2969 ····························e.row.RejectChanges();
2970 ····························ReadObject(e.pc, e.row, cl.ColumnNames, 0);
2971 ····························e.pc.NDOObjectState = NDOObjectState.Persistent;
2972 ························}
2973 ························else
2974 ························{
2975 ····························e.row.RejectChanges();
2976 ····························e.pc.NDOObjectState = NDOObjectState.Hollow;
2977 ························}
2978 ························break;
2979
2980 ····················default:
2981 ························throw new InternalException(2082, "Abort(): wrong state detected: " + e.pc.NDOObjectState + " id = " + e.pc.NDOObjectId.Dump());
2982 ························//Debug.Assert(false, "Object with wrong state detected: " + e.pc.NDOObjectState);
2983 ························//break;
2984 ················}
2985 ················if(hollowMode && e.pc.NDOObjectState == NDOObjectState.Persistent)
2986 ················{
2987 ····················hollowModeObjects.Add(e.pc);
2988 ················}
2989 ············}
2990 ············cache.UnlockAll();
2991 ············foreach(IPersistenceCapable pc in deletedObjects)
2992 ············{
2993 ················MakeObjectTransient(pc, true);
2994 ············}
2995 ············ds.Clear();
2996 ············mappingHandler.Clear();
2997 ············if(hollowMode)
2998 ············{
2999 ················MakeHollow(hollowModeObjects);
3000 ············}
3001
3002 ············this.relationChanges.Clear();
3003
3004
3005 ············await AbortTransactionAsync().ConfigureAwait( false );
3006 ········}
3007
3008
3009 ········/// <summary>
3010 ········/// Reset object to its transient state and remove it from the cache. Optinally, remove the object id to
3011 ········/// disable future access.
3012 ········/// </summary>
3013 ········/// <param name="pc"></param>
3014 ········/// <param name="removeId">Indicates if the object id should be nulled</param>
3015 ········private void MakeObjectTransient(IPersistenceCapable pc, bool removeId)
3016 ········{
3017 ············cache.Deregister(pc);
3018 ············// MakeTransient doesn't remove the ID, because delete makes objects transient and we need the id for the ChangeLog············
3019 ············if(removeId)
3020 ············{
3021 ················pc.NDOObjectId = null;
3022 ············}
3023 ············pc.NDOObjectState = NDOObjectState.Transient;
3024 ············pc.NDOStateManager = null;
3025 ········}
3026
3027 ········/// <summary>
3028 ········/// Makes an object transient.
3029 ········/// The object can be used afterwards, but changes will not be saved in the database.
3030 ········/// </summary>
3031 ········/// <remarks>
3032 ········/// Only persistent or hollow objects can be detached. Hollow objects are loaded to ensure valid data.
3033 ········/// </remarks>
3034 ········/// <param name="o">The object to detach.</param>
3035 ········public void MakeTransient(object o)
3036 ········{
3037 ············IPersistenceCapable pc = CheckPc(o);
3038 ············if(pc.NDOObjectState != NDOObjectState.Persistent && pc.NDOObjectState··!= NDOObjectState.Hollow)
3039 ············{
3040 ················throw new NDOException(79, "MakeTransient: Illegal state '" + pc.NDOObjectState + "' for this operation");
3041 ············}
3042
3043 ············if(pc.NDOObjectState··== NDOObjectState.Hollow)
3044 ············{
3045 ················LoadData(pc);
3046 ············}
3047 ············MakeObjectTransient(pc, true);
3048 ········}
3049
3050
3051 ········/// <summary>
3052 ········/// Make all objects of a list transient.
3053 ········/// </summary>
3054 ········/// <param name="list">the list of transient objects</param>
3055 ········public void MakeTransient(System.Collections.IList list)
3056 ········{
3057 ············foreach (IPersistenceCapable pc in list)
3058 ················MakeTransient(pc);
3059 ········}
3060
3061 ········/// <summary>
3062 ········/// Remove an object from the DB. Note that the object itself is not destroyed and may still be used.
3063 ········/// </summary>
3064 ········/// <param name="o">The object to remove</param>
3065 ········public void Delete(object o)
3066 ········{
3067 ············IPersistenceCapable pc = CheckPc(o);
3068 ············if (pc.NDOObjectState == NDOObjectState.Transient)
3069 ············{
3070 ················throw new NDOException( 120, "Can't delete transient object" );
3071 ············}
3072 ············if (pc.NDOObjectState != NDOObjectState.Deleted)
3073 ············{
3074 ················Delete(pc, true);
3075 ············}
3076 ········}
3077
3078
3079 ········private void LoadAllRelations(object o)
3080 ········{
3081 ············IPersistenceCapable pc = CheckPc(o);
3082 ············Class cl = GetClass(pc);
3083 ············foreach(Relation r in cl.Relations)
3084 ············{
3085 ················if (!pc.NDOGetLoadState(r.Ordinal))
3086 ····················LoadRelation(pc, r, true);
3087 ············}
3088 ········}
3089
3090
3091 ········/// <summary>
3092 ········/// Remove an object from the DB. Note that the object itself is not destroyed and may still be used.
3093 ········/// </summary>
3094 ········/// <remarks>
3095 ········/// If checkAssoziations it true, the object cannot be deleted if it is part of a bidirectional assoziation.
3096 ········/// This is the case if delete was called from user code. Internally, an object may be deleted because it is called from
3097 ········/// the parent object.
3098 ········/// </remarks>
3099 ········/// <param name="pc">the object to remove</param>
3100 ········/// <param name="checkAssoziations">true if child of a composition can't be deleted</param>
3101 ········private void Delete(IPersistenceCapable pc, bool checkAssoziations)
3102 ········{
3103 ············//Debug.WriteLine("Delete " + pc.NDOObjectId.Dump());
3104 ············//Debug.Indent();
3105 ············IDeleteNotifiable idn = pc as IDeleteNotifiable;
3106 ············if (idn != null)
3107 ················idn.OnDelete();
3108
3109 ············LoadAllRelations(pc);
3110 ············DeleteRelatedObjects(pc, checkAssoziations);
3111
3112 ············switch(pc.NDOObjectState)
3113 ············{
3114 ················case NDOObjectState.Transient:
3115 ····················throw new NDOException(80, "Cannot delete transient object: " + pc.NDOObjectId);
3116
3117 ················case NDOObjectState.Created:
3118 ····················DataRow row = cache.GetDataRow(pc);
3119 ····················row.Delete();
3120 ····················ArrayList cdosToDelete = new ArrayList();
3121 ····················foreach (IPersistenceCapable cdo in createdDirectObjects)
3122 ························if ((object)cdo == (object)pc)
3123 ····························cdosToDelete.Add(cdo);
3124 ····················foreach (object o in cdosToDelete)
3125 ························ObjectListManipulator.Remove(createdDirectObjects, o);
3126 ····················MakeObjectTransient(pc, true);
3127 ····················break;
3128 ················case NDOObjectState.Persistent:
3129 ····················if (!cache.IsLocked(pc)) // Deletes k�nnen durchaus mehrmals aufgerufen werden
3130 ························SaveObjectState(pc, true);
3131 ····················row = cache.GetDataRow(pc);
3132 ····················row.Delete();
3133 ····················pc.NDOObjectState = NDOObjectState.Deleted;
3134 ····················break;
3135 ················case NDOObjectState.Hollow:
3136 ····················if (!cache.IsLocked(pc)) // Deletes k�nnen durchaus mehrmals aufgerufen werden
3137 ························SaveFakeRow(pc);
3138 ····················row = cache.GetDataRow(pc);
3139 ····················row.Delete();
3140 ····················pc.NDOObjectState = NDOObjectState.Deleted;
3141 ····················break;
3142
3143 ················case NDOObjectState.PersistentDirty:
3144 ····················row = cache.GetDataRow(pc);
3145 ····················row.Delete();
3146 ····················pc.NDOObjectState··= NDOObjectState.Deleted;
3147 ····················break;
3148
3149 ················case NDOObjectState.Deleted:
3150 ····················break;
3151 ············}
3152
3153 ············//Debug.Unindent();
3154 ········}
3155
3156
3157 ········/// <summary>
3158 ········/// Finds the pending entry, which inserts or deletes the row of the mapping table for the given objects.
3159 ········/// </summary>
3160 ········/// <remarks>
3161 ········/// Both relations of a bidirectional n:m relation use the same mapping table.
3162 ········/// So an entry created through the foreign relation describes the same row.
3163 ········/// </remarks>
3164 ········private MappingTableEntry FindMappingTableEntry(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
3165 ········{
3166 ············foreach(MappingTableEntry e in createdMappingTableObjects)
3167 ············{
3168 ················if (e.Relation == r && e.ParentObject == pc && e.RelatedObject == relObj)
3169 ····················return e;
3170 ················if (r.Bidirectional && e.Relation == r.ForeignRelation && e.ParentObject == relObj && e.RelatedObject == pc)
3171 ····················return e;
3172 ············}
3173 ············return null;
3174 ········}
3175
3176 ········/// <summary>
3177 ········/// Makes sure, that an object is added only once to a relation with a mapping table.
3178 ········/// </summary>
3179 ········/// <remarks>
3180 ········/// The mapping table has a unique index on the columns of both sides. A second entry would fail while saving.
3181 ········/// </remarks>
3182 ········private void CheckDuplicateMappingTableEntry(IPersistenceCapable pc, Relation r, IPersistenceCapable relObj)
3183 ········{
3184 ············MappingTableEntry mte = FindMappingTableEntry(pc, r, relObj);
3185 ············bool isDuplicate;
3186 ············if (mte != null)
3187 ············{
3188 ················isDuplicate = !mte.DeleteEntry;
3189 ············}
3190 ············else
3191 ············{
3192 ················// The relation list contains the objects of the existing rows. If one of the objects is created,
3193 ················// a row can't exist and the list might contain relObj already, because MakePersistent adds the objects of the list.
3194 ················isDuplicate = r.Multiplicity == RelationMultiplicity.List
3195 ····················&& pc.NDOObjectState != NDOObjectState.Created
3196 ····················&& relObj.NDOObjectState != NDOObjectState.Created
3197 ····················&& pc.NDOGetLoadState(r.Ordinal)
3198 ····················&& mappings.GetRelationContainer(pc, r) is IList l
3199 ····················&& ObjectListManipulator.Contains(l, relObj);
3200 ············}
3201
3202 ············if (isDuplicate)
3203 ················throw new NDOException(123, "The object " + relObj.NDOObjectId.Dump() + " is already part of the relation " + pc.GetType().FullName + "." + r.FieldName + " of the object " + pc.NDOObjectId.Dump() + ". An object can't be added twice to a relation with a mapping table.");
3204 ········}
3205
3206 ········private void DeleteMappingTableEntry(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3207 ········{
3208 ············MappingTableEntry mte = FindMappingTableEntry(pc, r, child);
3209
3210 ············if (mte != null)
3211 ············{
3212 ················// Removing an object, which was added in the same transaction, cancels the insertion.
3213 ················if (!mte.DeleteEntry)
3214 ····················createdMappingTableObjects.Remove(mte);
3215 ············}
3216 ············else if (pc.NDOObjectState != NDOObjectState.Created && child.NDOObjectState != NDOObjectState.Created)
3217 ············{
3218 ················createdMappingTableObjects.Add(new MappingTableEntry(pc, child, r, true));
3219 ············}
3220 ········}
3221
3222 ········private void DeleteOrNullForeignRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3223 ········{
3224 ············// Two tasks: a) Null the foreign key
3225 ············//··············b) remove the element from the foreign container
3226
3227 ············if (!r.Bidirectional)
3228 ················return;
3229
3230 ············// this keeps the oid valid
3231 ············if (GetClass(child.GetType()).Oid.IsDependent)
3232 ················return;
3233
3234 ············if(r.ForeignRelation.Multiplicity == RelationMultiplicity.Element)
3235 ············{
3236 ················LoadAndMarkDirty(child);
3237 ················mappings.SetRelationField(child, r.ForeignRelation.FieldName, null);
3238 ············}
3239 ············else //if(r.Multiplicity == RelationMultiplicity.List &&
3240 ················// r.ForeignRelation.Multiplicity == RelationMultiplicity.List)··
3241 ············{
3242 ················if (!child.NDOGetLoadState(r.ForeignRelation.Ordinal))
3243 ····················LoadRelation(child, r.ForeignRelation, true);
3244 ················IList l = mappings.GetRelationContainer(child, r.ForeignRelation);
3245 ················if (l == null)
3246 ····················throw new NDOException(67, "Can't remove object from the list " + child.GetType().FullName + "." + r.ForeignRelation.FieldName + ". The list is null.");
3247 ················ObjectListManipulator.Remove(l, pc);
3248 ················// Don't need to delete the mapping table entry, because that was done
3249 ················// through the parent.
3250 ············}
3251 ········}
3252
3253 ········private void DeleteOrNullRelation(IPersistenceCapable pc, Relation r, IPersistenceCapable child)
3254 ········{
3255 ············// 1) Element····nomap····ass
3256 ············// 2) Element····nomap····comp
3257 ············// 3) Element····map········ass
3258 ············// 4) Element····map········comp
3259 ············// 5) List········nomap····ass
3260 ············// 6) List········nomap····comp
3261 ············// 7) List········map········ass
3262 ············// 8) List········map········comp
3263
3264 ············// Two tasks: Null foreign key and, if Composition, delete the child
3265
3266 ············// If Mapping Table, delete the entry - 3,7
3267 ············// If List and assoziation, null the foreign key in the foreign class - 5
3268 ············// If Element, null the foreign key in the own class 1,2,3,4
3269 ············// If composition, delete the child 2,4,6,8
3270
3271 ············// If the relObj is newly created
3272 ············ObjectListManipulator.Remove(createdDirectObjects, child);
3273 ············Class childClass = GetClass(child);
3274
3275 ············if (r.MappingTable != null)··// 3,7
3276 ············{················
3277 ················DeleteMappingTableEntry(pc, r, child);
3278 ············}
3279 ············else if (r.Multiplicity == RelationMultiplicity.List
3280 ················&& !r.Composition && !childClass.Oid.IsDependent) // 5
3281 ············{················
3282 ················LoadAndMarkDirty(child);
3283 ················DataRow row = this.cache.GetDataRow(child);
3284 ················foreach (ForeignKeyColumn fkColumnn in r.ForeignKeyColumns)
3285 ················{
3286 ····················row[fkColumnn.Name] = DBNull.Value;
3287 ····················child.NDOLoadState.ReplaceRowInfo(fkColumnn.Name, DBNull.Value);
3288 ················}
3289 ············}
3290 ············else if (r.Multiplicity == RelationMultiplicity.Element) // 1,2,3,4
3291 ············{
3292 ················LoadAndMarkDirty(pc);
3293 ············}
3294 ············if (r.Composition || childClass.Oid.IsDependent)
3295 ············{
3296 #if DEBUG
3297 ················if (child.NDOObjectState == NDOObjectState.Transient)
3298 ····················Debug.WriteLine("***** Object shouldn't be transient: " + child.GetType().FullName);
3299 #endif
3300 ················// Deletes the foreign key in case of List multiplicity
3301 ················// In case of Element multiplicity, the parent is either deleted,
3302 ················// or RemoveRelatedObject is called because the relation has been nulled.
3303 ················Delete(child);··
3304 ············}
3305 ········}
3306
3307 ········/// <summary>
3308 ········/// Remove a related object
3309 ········/// </summary>
3310 ········/// <param name="pc"></param>
3311 ········/// <param name="r"></param>
3312 ········/// <param name="child"></param>
3313 ········/// <param name="calledFromStateManager"></param>
3314 ········protected virtual void InternalRemoveRelatedObject(IPersistenceCapable pc, Relation r, IPersistenceCapable child, bool calledFromStateManager)
3315 ········{
3316 ············//TODO: We need a relation management, which is independent of
3317 ············//the state management of an object. At the moment the relation
3318 ············//lists or elements are cached for restore, if an object is marked dirty.
3319 ············//Thus we have to mark dirty our parent object in any case at the moment.
3320 ············if (calledFromStateManager)
3321 ················MarkDirty(pc);
3322
3323 ············// Object can be deleted in an OnDelete-Handler
3324 ············if (child.NDOObjectState == NDOObjectState.Deleted)
3325 ················return;
3326 ············//············Debug.WriteLine("InternalRemoveRelatedObject " + pc.GetType().Name + " " + r.FieldName + " " + child.GetType());
3327 ············// Preconditions
3328 ············// This is called either by DeleteRelatedObjects or by RemoveRelatedObject
3329 ············// The Object state is checked there
3330
3331 ············// If there is a composition in the opposite direction
3332 ············// && the other direction hasn't been processed
3333 ············// throw an exception.
3334 ············// If an exception is thrown at this point, have a look at IsLocked....
3335 ············if (r.Bidirectional && r.ForeignRelation.Composition
3336 ················&& !removeLock.IsLocked(child, r.ForeignRelation, pc))
3337 ················throw new NDOException(82, "Cannot remove related object " + child.GetType().FullName + " from parent " + pc.NDOObjectId.Dump() + ". Object must be removed through the parent.");
3338
3339 ············if (!removeLock.GetLock(pc, r, child))
3340 ················return;
3341
3342 ············try
3343 ············{
3344 ················// must be in this order, since the child
3345 ················// can be deleted in DeleteOrNullRelation
3346 ················//if (changeForeignRelations)
3347 ················DeleteOrNullForeignRelation(pc, r, child);
3348 ················DeleteOrNullRelation(pc, r, child);
3349 ············}
3350 ············finally
3351 ············{
3352 ················removeLock.Unlock(pc, r, child);
3353 ············}
3354
3355 ············this.relationChanges.Add( new RelationChangeRecord( pc, child, r.FieldName, false ) );
3356 ········}
3357
3358 ········private void DeleteRelatedObjects2(IPersistenceCapable pc, Class parentClass, bool checkAssoziations, Relation r)
3359 ········{
3360 ············//············Debug.WriteLine("DeleteRelatedObjects2 " + pc.GetType().Name + " " + r.FieldName);
3361 ············//············Debug.Indent();
3362 ············if (r.Multiplicity == RelationMultiplicity.Element)
3363 ············{
3364 ················IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
3365 ················if(child != null)
3366 ················{
3367 ····················//····················if(checkAssoziations && r.Bidirectional && !r.Composition)
3368 ····················//····················{
3369 ····················//························if (!r.ForeignRelation.Composition)
3370 ····················//························{
3371 ····················//····························mappings.SetRelationField(pc, r.FieldName, null);
3372 ····················//····························mappings.SetRelationField(child, r.ForeignRelation.FieldName, null);
3373 ····················//························}
3374 ····················//····························//System.Diagnostics.Debug.WriteLine("Nullen: pc = " + pc.GetType().Name + " child = " + child.GetType().Name);
3375 ····················//························else
3376 ····················//····························throw new NDOException(83, "Can't remove object of type " + pc.GetType().FullName + "; It is contained by an object of type " + child.GetType().FullName);
3377 ····················//····················}
3378 ····················InternalRemoveRelatedObject(pc, r, child, false);
3379 ················}
3380 ············}
3381 ············else
3382 ············{
3383 ················IList list = mappings.GetRelationContainer(pc, r);
3384 ················if(list != null && list.Count > 0)
3385 ················{
3386 ····················//····················if(checkAssoziations && r.Bidirectional && !r.Composition)
3387 ····················//····················{
3388 ····················//························throw new xxNDOException(84, "Cannot delete object " + pc.NDOObjectId + " in an assoziation. Remove related objects first.");
3389 ····················//····················}
3390 ····················// Since RemoveRelatedObjects probably changes the list,
3391 ····················// we iterate through a copy of the list.
3392 ····················ArrayList al = new ArrayList(list);
3393 ····················foreach(IPersistenceCapable relObj in al)
3394 ····················{
3395 ························InternalRemoveRelatedObject(pc, r, relObj, false);
3396 ····················}
3397 ················}
3398 ············}
3399 ············//············Debug.Unindent();
3400 ········}
3401
3402 ········/// <summary>
3403 ········/// Remove all related objects from a parent.
3404 ········/// </summary>
3405 ········/// <param name="pc">the parent object</param>
3406 ········/// <param name="checkAssoziations"></param>
3407 ········private void DeleteRelatedObjects(IPersistenceCapable pc, bool checkAssoziations)
3408 ········{
3409 ············//············Debug.WriteLine("DeleteRelatedObjects " + pc.NDOObjectId.Dump());
3410 ············//············Debug.Indent();
3411 ············// delete all related objects:
3412 ············Class parentClass = GetClass(pc);
3413 ············// Remove Assoziations first
3414 ············foreach(Relation r in parentClass.Relations)
3415 ············{
3416 ················if (!r.Composition)
3417 ····················DeleteRelatedObjects2(pc, parentClass, checkAssoziations, r);
3418 ············}
3419 ············foreach(Relation r in parentClass.Relations)
3420 ············{
3421 ················if (r.Composition)
3422 ····················DeleteRelatedObjects2(pc, parentClass, checkAssoziations, r);
3423 ············}
3424
3425 ············//············Debug.Unindent();
3426 ········}
3427
3428 ········/// <summary>
3429 ········/// Delete a list of objects
3430 ········/// </summary>
3431 ········/// <param name="list">the list of objects to remove</param>
3432 ········public void Delete(IList list)
3433 ········{
3434 ············for (int i = 0; i < list.Count; i++)
3435 ············{
3436 ················IPersistenceCapable pc = (IPersistenceCapable) list[i];
3437 ················Delete(pc);
3438 ············}
3439 ········}
3440
3441 ········/// <summary>
3442 ········/// Make object hollow. All relations will be unloaded and object data will be
3443 ········/// newly fetched during the next touch of a persistent field.
3444 ········/// </summary>
3445 ········/// <param name="o"></param>
3446 ········public virtual void MakeHollow(object o)
3447 ········{
3448 ············IPersistenceCapable pc = CheckPc(o);
3449 ············MakeHollow(pc, false);
3450 ········}
3451
3452 ········/// <summary>
3453 ········/// Make the object hollow if it is persistent. Unload all complex data.
3454 ········/// </summary>
3455 ········/// <param name="o"></param>
3456 ········/// <param name="recursive">if true then unload related objects as well</param>
3457 ········public virtual void MakeHollow(object o, bool recursive)
3458 ········{
3459 ············IPersistenceCapable pc = CheckPc(o);
3460 ············if(pc.NDOObjectState == NDOObjectState.Hollow)
3461 ················return;
3462 ············if(pc.NDOObjectState != NDOObjectState.Persistent)
3463 ············{
3464 ················throw new NDOException(85, "MakeHollow: Illegal state for this operation (" + pc.NDOObjectState.ToString() + ")");
3465 ············}
3466 ············pc.NDOObjectState = NDOObjectState.Hollow;
3467 ············MakeRelationsHollow(pc, recursive);
3468 ········}
3469
3470 ········/// <summary>
3471 ········/// Make all objects of a list hollow.
3472 ········/// </summary>
3473 ········/// <param name="list">the list of objects that should be made hollow</param>
3474 ········public virtual void MakeHollow(System.Collections.IList list)
3475 ········{
3476 ············MakeHollow(list, false);
3477 ········}
3478
3479 ········/// <summary>
3480 ········/// Make all objects of a list hollow.
3481 ········/// </summary>
3482 ········/// <param name="list">the list of objects that should be made hollow</param>
3483 ········/// <param name="recursive">if true then unload related objects as well</param>
3484 ········public void MakeHollow(System.Collections.IList list, bool recursive)
3485 ········{
3486 ············foreach (IPersistenceCapable pc in list)
3487 ················MakeHollow(pc, recursive);················
3488 ········}
3489
3490 ········/// <summary>
3491 ········/// Make all unlocked objects in the cache hollow.
3492 ········/// </summary>
3493 ········public virtual void MakeAllHollow()
3494 ········{
3495 ············foreach(var pc in cache.UnlockedObjects)
3496 ············{
3497 ················MakeHollow(pc, false);
3498 ············}
3499 ········}
3500
3501 ········/// <summary>
3502 ········/// Make relations hollow.
3503 ········/// </summary>
3504 ········/// <param name="pc">The parent object</param>
3505 ········/// <param name="recursive">If true, the function unloads related objects as well.</param>
3506 ········private void MakeRelationsHollow(IPersistenceCapable pc, bool recursive)
3507 ········{
3508 ············Class c = GetClass(pc);
3509 ············foreach(Relation r in c.Relations)
3510 ············{
3511 ················if (r.Multiplicity == RelationMultiplicity.Element)
3512 ················{
3513 ····················mappings.SetRelationField(pc, r.FieldName, null);
3514 ····················//····················IPersistenceCapable child = (IPersistenceCapable) mappings.GetRelationField(pc, r.FieldName);
3515 ····················//····················if((null != child) && recursive)
3516 ····················//····················{
3517 ····················//························MakeHollow(child, true);
3518 ····················//····················}
3519 ················}
3520 ················else
3521 ················{
3522 ····················if (!pc.NDOGetLoadState(r.Ordinal))
3523 ························continue;
3524 ····················// Help GC by clearing lists
3525 ····················IList l = mappings.GetRelationContainer(pc, r);
3526 ····················if(l != null)
3527 ····················{
3528 ························if(recursive)
3529 ························{
3530 ····························MakeHollow(l, true);
3531 ························}
3532 ························l.Clear();
3533 ····················}
3534 ····················// Hollow relation
3535 ····················mappings.SetRelationContainer(pc, r, null);
3536 ················}
3537 ············}
3538 ············ClearRelationState(pc);
3539 ········}
3540
3541 ········private void ClearRelationState(IPersistenceCapable pc)
3542 ········{
3543 ············Class cl = GetClass(pc);
3544 ············foreach(Relation r in cl.Relations)
3545 ················pc.NDOSetLoadState(r.Ordinal, false);
3546 ········}
3547
3548 ········private void SetRelationState(IPersistenceCapable pc)
3549 ········{
3550 ············Class cl = GetClass(pc);
3551 ············// Due to a bug in the enhancer the constructors are not always patched right,
3552 ············// so NDOLoadState might be uninitialized
3553 ············if (pc.NDOLoadState == null)
3554 ············{
3555 ················FieldInfo fi = new BaseClassReflector(pc.GetType()).GetField("_ndoLoadState", BindingFlags.Instance | BindingFlags.NonPublic);
3556 ················if (fi == null)
3557 ····················throw new InternalException(3131, "pm.SetRelationState: No FieldInfo for _ndoLoadState");
3558 ················fi.SetValue(pc, new LoadState());
3559 ············}
3560
3561 ············// After serialization the relation load state is null
3562 ············if (pc.NDOLoadState.RelationLoadState == null)
3563 ················pc.NDOLoadState.RelationLoadState = new BitArray(LoadState.RelationLoadStateSize);
3564 ············foreach(Relation r in cl.Relations)
3565 ················pc.NDOSetLoadState(r.Ordinal, true);
3566 ········}
3567
3568 ········/// <summary>
3569 ········/// Creates an object of a given type and resolves constructor parameters using the container.
3570 ········/// </summary>
3571 ········/// <param name="t">The type of the persistent object</param>
3572 ········/// <returns></returns>
3573 ········public IPersistenceCapable CreateObject(Type t)
3574 ········{
3575 ············return (IPersistenceCapable) ActivatorUtilities.CreateInstance( ServiceProvider, t );
3576 ········}
3577
3578 ········/// <summary>
3579 ········/// Creates an object of a given type and resolves constructor parameters using the container.
3580 ········/// </summary>
3581 ········/// <typeparam name="T">The type of the object to create.</typeparam>
3582 ········/// <returns></returns>
3583 ········public T CreateObject<T>()
3584 ········{
3585 ············return (T)CreateObject( typeof( T ) );
3586 ········}
3587
3588 ········/// <summary>
3589 ········/// Finds an object in the object cache and loads the object from the database
3590 ········/// in case of a cache miss.
3591 ········/// </summary>
3592 ········/// <param name="shortId"></param>
3593 ········/// <returns>A persistent object</returns>
3594 ········public async Task <IPersistenceCapable> GetObjectByShortIdAsync(string shortId)
3595 ········{
3596 ············var pc = FindObject(shortId);
3597 ············if (pc.NDOObjectState == NDOObjectState.Hollow)
3598 ················await LoadDataAsync( pc ).ConfigureAwait(false);
3599 ············return pc;
3600 ········}
3601
3602 ········/// <summary>
3603 ········/// Gets the requested object. It first builds an ObjectId using the type and the
3604 ········/// key data. Then it uses FindObject to retrieve the object. No database access
3605 ········/// is performed.
3606 ········/// </summary>
3607 ········/// <param name="t">The type of the object to retrieve.</param>
3608 ········/// <param name="keyData">The key value to build the object id.</param>
3609 ········/// <returns>A hollow object</returns>
3610 ········/// <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>
3611 ········public IPersistenceCapable FindObject(Type t, object keyData)
3612 ········{
3613 ············ObjectId oid = ObjectIdFactory.NewObjectId(t, GetClass(t), keyData, this.typeManager);
3614 ············return FindObject(oid);
3615 ········}
3616
3617 ········/// <summary>
3618 ········/// Finds an object using a short id.
3619 ········/// </summary>
3620 ········/// <param name="encodedShortId"></param>
3621 ········/// <returns></returns>
3622 ········public IPersistenceCapable FindObject(string encodedShortId)
3623 ········{
3624 ············string shortId = encodedShortId.Decode();
3625 ············string[] arr = shortId.Split( '-' );
3626 ············if (arr.Length != 3)
3627 ················throw new ArgumentException( "The format of the string is not valid", "shortId" );
3628 ············Type t = shortId.GetObjectType(this);··// try readable format
3629 ············if (t == null)
3630 ············{
3631 ················int typeCode = 0;
3632 ················if (!int.TryParse( arr[2], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out typeCode ))
3633 ····················throw new ArgumentException( "The string doesn't represent a loadable type", "shortId" );
3634 ················t = this.typeManager[typeCode];
3635 ················if (t == null)
3636 ····················throw new ArgumentException( "The string doesn't represent a loadable type", "shortId" );
3637 ············}
3638
3639 ············Class cls = GetClass( t );
3640 ············if (cls == null)
3641 ················throw new ArgumentException( "The type identified by the string is not persistent or is not managed by the given mapping file", "shortId" );
3642
3643 ············object[] keydata = new object[cls.Oid.OidColumns.Count];
3644 ············string[] oidValues = arr[2].Split( ' ' );
3645
3646 ············int i = 0;
3647 ············foreach (var oidValue in oidValues)
3648 ············{
3649 ················Type oidType = cls.Oid.OidColumns[i].SystemType;
3650 ················if (oidType == typeof( int ))
3651 ················{
3652 ····················int key;
3653 ····················if (!int.TryParse( oidValue, out key ))
3654 ························throw new ArgumentException( $"The ShortId value at index {i} doesn't contain an int value", nameof(encodedShortId) );
3655 ····················if (key > (int.MaxValue >> 1))
3656 ························key = -(int.MaxValue - key);
3657 ····················keydata[i] = key;
3658 ················}
3659 ················else if (oidType == typeof( Guid ))
3660 ················{
3661 ····················Guid key;
3662 ····················if (!Guid.TryParse( oidValue, out key ))
3663 ························throw new ArgumentException( $"The ShortId value at index {i} doesn't contain an Guid value", nameof( encodedShortId ) );
3664 ····················keydata[i] = key;
3665 ················}
3666 ················else if (oidType == typeof( string ))
3667 ················{
3668 ····················keydata[i] = oidValue;
3669 ················}
3670 ················else
3671 ················{
3672 ····················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 ) );
3673 ················}
3674
3675 ················i++;
3676 ············}
3677
3678 ············if (keydata.Length == 1)
3679 ················return FindObject( t, keydata[0] );
3680
3681 ············return FindObject( t, keydata );············
3682 ········}
3683
3684 ········/// <summary>
3685 ········/// Gets the requested object. If it is in the cache, the cached object is returned, otherwise, a new (hollow)
3686 ········/// instance of the object is returned. In either case, the DB is not accessed!
3687 ········/// </summary>
3688 ········/// <param name="id">Object id</param>
3689 ········/// <returns>The object to retrieve in hollow state</returns>········
3690 ········public IPersistenceCapable FindObject(ObjectId id)
3691 ········{
3692 ············if(id == null)
3693 ············{
3694 ················throw new ArgumentNullException("id");
3695 ············}
3696
3697 ············if(!id.IsValid())
3698 ············{
3699 ················throw new NDOException(86, "FindObject: Invalid object id. Object does not exist");
3700 ············}
3701
3702 ············IPersistenceCapable pc = cache.GetObject(id);
3703 ············if(pc == null)
3704 ············{
3705 ················pc = CreateObject(id.Id.Type);
3706 ················pc.NDOObjectId = id;
3707 ················pc.NDOStateManager = sm;
3708 ················pc.NDOObjectState = NDOObjectState.Hollow;
3709 ················cache.UpdateCache(pc);
3710 ············}
3711 ············return pc;
3712 ········}
3713
3714
3715 ········/// <summary>
3716 ········/// Reload an object from the database.
3717 ········/// </summary>
3718 ········/// <param name="o">The object to be reloaded.</param>
3719 ········public void Refresh(object o)
3720 ········{
3721 ············RefreshAsync( o ).ConfigureAwait( false ).GetAwaiter().GetResult();
3722 ········}
3723
3724 ········/// <summary>
3725 ········/// Reload an object from the database asynchronously.
3726 ········/// </summary>
3727 ········/// <param name="o">The object to be reloaded.</param>
3728 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3729 ········public virtual async Task RefreshAsync( object o, CancellationToken cancellationToken = default )
3730 ········{
3731 ············using (EnterOperation())
3732 ············{
3733 ················await RefreshInternalAsync( o, cancellationToken ).ConfigureAwait( false );
3734 ············}
3735 ········}
3736
3737 ········async Task RefreshInternalAsync( object o, CancellationToken cancellationToken )
3738 ········{
3739 ············IPersistenceCapable pc = CheckPc(o);
3740 ············if(pc.NDOObjectState == NDOObjectState.Transient || pc.NDOObjectState == NDOObjectState.Deleted)
3741 ············{
3742 ················throw new NDOException(87, "Refresh: Illegal state " + pc.NDOObjectState + " for this operation");
3743 ············}
3744
3745 ············if(pc.NDOObjectState == NDOObjectState.Created || pc.NDOObjectState == NDOObjectState.PersistentDirty)
3746 ················return; // Cannot update objects in current transaction
3747
3748 ············MakeHollow(pc);
3749 ············await LoadDataAsync( pc, cancellationToken ).ConfigureAwait( false );
3750 ········}
3751
3752 ········/// <summary>
3753 ········/// Refresh a list of objects.
3754 ········/// </summary>
3755 ········/// <param name="list">The list of objects to be refreshed.</param>
3756 ········public void Refresh(IList list)
3757 ········{
3758 ············RefreshAsync( list ).ConfigureAwait( false ).GetAwaiter().GetResult();
3759 ········}
3760
3761 ········/// <summary>
3762 ········/// Refresh a list of objects asynchronously.
3763 ········/// </summary>
3764 ········/// <param name="list">The list of objects to be refreshed.</param>
3765 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3766 ········/// <remarks>The objects are refreshed sequentially.</remarks>
3767 ········public virtual async Task RefreshAsync( IList list, CancellationToken cancellationToken = default )
3768 ········{
3769 ············using (EnterOperation())
3770 ············{
3771 ················foreach (IPersistenceCapable pc in list)
3772 ····················await RefreshAsync( (object) pc, cancellationToken ).ConfigureAwait( false );
3773 ············}
3774 ········}
3775
3776 ········/// <summary>
3777 ········/// Refreshes all unlocked objects in the cache.
3778 ········/// </summary>
3779 ········public void RefreshAll()
3780 ········{
3781 ············RefreshAllAsync().ConfigureAwait( false ).GetAwaiter().GetResult();
3782 ········}
3783
3784 ········/// <summary>
3785 ········/// Refreshes all unlocked objects in the cache asynchronously.
3786 ········/// </summary>
3787 ········/// <param name="cancellationToken">A token to cancel the operation</param>
3788 ········public virtual Task RefreshAllAsync( CancellationToken cancellationToken = default )
3789 ········{
3790 ············return RefreshAsync( cache.UnlockedObjects.ToList(), cancellationToken );
3791 ········}
3792
3793 ········/// <summary>
3794 ········/// Closes the PersistenceManager and releases all resources.
3795 ········/// </summary>
3796 ········public override async Task CloseAsync()
3797 ········{
3798 ············if (this.isClosing)
3799 ················return;
3800 ············this.isClosing = true;
3801 ············await TransactionScope.DisposeAsync().ConfigureAwait( false );
3802 ············UnloadCache();
3803 ············await base.CloseAsync().ConfigureAwait( false );
3804 ········}
3805
3806 ········internal void LogIfVerbose( string msg )
3807 ········{
3808 ············if (Logger != null && Logger.IsEnabled( LogLevel.Debug ))
3809 ················Logger.LogDebug( msg );
3810 ········}
3811
3812
3813 ········#endregion
3814
3815
3816
3817 #region Query engine
3818
3819
3820 ········/// <summary>
3821 ········/// Returns a virtual table for Linq queries.
3822 ········/// </summary>
3823 ········/// <typeparam name="T"></typeparam>
3824 ········/// <returns></returns>
3825 ········public VirtualTable<T> Objects<T>() //where T: IPersistenceCapable
3826 ········{
3827 ············return new VirtualTable<T>( this );
3828 ········}
3829
3830 ········
3831 ········/// <summary>
3832 ········/// Suppose, you had a directed 1:n relation from class A to class B. If you load an object of type B,
3833 ········/// 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
3834 ········/// a relation to A the foreign key would get lost if we discard the row after building the B object. To
3835 ········/// not lose the foreign key it will be stored as part of the object.
3836 ········/// </summary>
3837 ········/// <param name="cl"></param>
3838 ········/// <param name="pc"></param>
3839 ········/// <param name="row"></param>
3840 ········void ReadLostForeignKeysFromRow(Class cl, IPersistenceCapable pc, DataRow row)
3841 ········{
3842 ············if (cl.FKColumnNames != null && pc.NDOLoadState != null)
3843 ············{
3844 ················//················Debug.WriteLine("GetLostForeignKeysFromRow " + pc.NDOObjectId.Dump());
3845 ················KeyValueList kvl = new KeyValueList(cl.FKColumnNames.Count());
3846 ················foreach(string colName in cl.FKColumnNames)
3847 ····················kvl.Add(new KeyValuePair(colName, row[colName]));
3848 ················pc.NDOLoadState.LostRowInfo = kvl;················
3849 ············}
3850 ········}
3851
3852 ········/// <summary>
3853 ········/// Writes information into the data row, which cannot be stored in the object.
3854 ········/// </summary>
3855 ········/// <param name="cl"></param>
3856 ········/// <param name="pc"></param>
3857 ········/// <param name="row"></param>
3858 ········protected virtual void WriteLostForeignKeysToRow(Class cl, IPersistenceCapable pc, DataRow row)
3859 ········{
3860 ············if (cl.FKColumnNames != null)
3861 ············{
3862 ················//················Debug.WriteLine("WriteLostForeignKeys " + pc.NDOObjectId.Dump());
3863 ················KeyValueList kvl = (KeyValueList)pc.NDOLoadState.LostRowInfo;
3864 ················if (kvl == null)
3865 ····················throw new NDOException(88, "Can't find foreign keys for the relations of the object " + pc.NDOObjectId.Dump());
3866 ················foreach (KeyValuePair pair in kvl)
3867 ····················row[(string) pair.Key] = pair.Value;
3868 ············}
3869 ········}
3870
3871 ········void Row2Object(Class cl, IPersistenceCapable pc, DataRow row)
3872 ········{
3873 ············ReadObject(pc, row, cl.ColumnNames, 0);
3874 ············ReadTimeStamp(cl, pc, row);
3875 ············ReadLostForeignKeysFromRow(cl, pc, row);
3876 ············LoadRelated1To1Objects(pc, row);
3877 ············pc.NDOObjectState = NDOObjectState.Persistent;
3878 ········}
3879
3880
3881 ········/// <summary>
3882 ········/// Convert a data table to objects. Note that the table might only hold objects of the specified type.
3883 ········/// </summary>
3884 ········internal IList DataTableToIList(Type t, ICollection rows, bool hollow)
3885 ········{
3886 ············IList queryResult = GenericListReflector.CreateList(t, rows.Count);
3887 ············if (rows.Count == 0)
3888 ················return queryResult;
3889
3890 ············IList callbackObjects = new ArrayList();
3891 ············Class cl = GetClass(t);
3892 ············if (t.IsGenericTypeDefinition)
3893 ············{
3894 ················if (cl.TypeNameColumn == null)
3895 ····················throw new NDOException(104, "No type name column defined for generic type '" + t.FullName + "'. Check your mapping file.");
3896 ················IEnumerator en = rows.GetEnumerator();
3897 ················en.MoveNext();··// Move to the first element
3898 ················DataRow testrow = (DataRow)en.Current;
3899 ················if (testrow.Table.Columns[cl.TypeNameColumn.Name] == null)
3900 ····················throw new InternalException(3333, "DataTableToIList: TypeNameColumn isn't defined in the schema.");
3901 ············}
3902
3903 ············foreach(DataRow row in rows)
3904 ············{
3905 ················Type concreteType = t;
3906 ················if (t.IsGenericTypeDefinition)··// type information is in the row
3907 ················{
3908 ····················if (row[cl.TypeNameColumn.Name] == DBNull.Value)
3909 ····················{
3910 ························ObjectId tempid = ObjectIdFactory.NewObjectId(t, cl, row, this.typeManager);
3911 ························throw new NDOException(105, "Null entry in the TypeNameColumn of the type '" + t.FullName + "'. Oid = " + tempid.ToString());
3912 ····················}
3913 ····················string typeStr = (string)row[cl.TypeNameColumn.Name];
3914 ····················concreteType = Type.GetType(typeStr);
3915 ····················if (concreteType == null)
3916 ························throw new NDOException(106, "Can't load generic type " + typeStr);
3917 ················}
3918 ················ObjectId id = ObjectIdFactory.NewObjectId(concreteType, cl, row, this.typeManager);
3919 ················IPersistenceCapable pc = cache.GetObject(id);················
3920 ················if(pc == null)
3921 ················{
3922 ····················pc = CreateObject( concreteType );
3923 ····················pc.NDOObjectId = id;
3924 ····················pc.NDOStateManager = sm;
3925 ····················// If the object shouldn't be hollow, this will be overwritten later.
3926 ····················pc.NDOObjectState = NDOObjectState.Hollow;
3927 ················}
3928 ················// If we have found a non hollow object, the time stamp remains the old one.
3929 ················// In every other case we use the new time stamp.
3930 ················// Note, that there could be a hollow object in the cache.
3931 ················// We need the time stamp in hollow objects in order to correctly
3932 ················// delete objects using fake rows.
3933 ················if (pc.NDOObjectState == NDOObjectState.Hollow)
3934 ················{
3935 ····················ReadTimeStamp(cl, pc, row);
3936 ················}
3937 ················if(!hollow && pc.NDOObjectState != NDOObjectState.PersistentDirty)
3938 ················{
3939 ····················Row2Object(cl, pc, row);
3940 ····················if ((pc as IPersistenceNotifiable) != null)
3941 ························callbackObjects.Add(pc);
3942 ················}
3943
3944 ················cache.UpdateCache(pc);
3945 ················queryResult.Add(pc);
3946 ············}
3947 ············// Make shure this is the last statement before returning
3948 ············// to the caller, so the user can recursively use persistent
3949 ············// objects
3950 ············foreach(IPersistenceNotifiable ipn in callbackObjects)
3951 ················ipn.OnLoaded();
3952
3953 ············return queryResult;
3954 ········}
3955
3956 #endregion
3957
3958 #region Cache Management
3959 ········/// <summary>
3960 ········/// Remove all unused entries from the cache.
3961 ········/// </summary>
3962 ········public void CleanupCache()
3963 ········{
3964 ············GC.Collect(GC.MaxGeneration);
3965 ············GC.WaitForPendingFinalizers();
3966 ············cache.Cleanup();
3967 ········}
3968
3969 ········/// <summary>
3970 ········/// Remove all unlocked objects from the cache. Use with care!
3971 ········/// </summary>
3972 ········public void UnloadCache()
3973 ········{
3974 ············cache.Unload();
3975 ········}
3976 #endregion
3977
3978 ········/// <summary>
3979 ········/// Default encryption key for NDO
3980 ········/// </summary>
3981 ········/// <remarks>
3982 ········/// We recommend strongly to use an own encryption key, which can be set with this property.
3983 ········/// </remarks>
3984 ········public virtual byte[] EncryptionKey
3985 ········{
3986 ············get
3987 ············{
3988 ················if (this.encryptionKey == null)
3989 ····················this.encryptionKey = new byte[] { 0x09,0xA2,0x79,0x5C,0x99,0xFF,0xCB,0x8B,0xA3,0x37,0x76,0xC8,0xA6,0x5D,0x6D,0x66,
3990 ······················································0xE2,0x74,0xCF,0xF0,0xF7,0xEA,0xC4,0x82,0x1E,0xD5,0x19,0x4C,0x5A,0xB4,0x89,0x4D };
3991 ················return this.encryptionKey;
3992 ············}
3993 ············set { this.encryptionKey = value; }
3994 ········}
3995
3996 ········/// <summary>
3997 ········/// Hollow mode: If true all objects are made hollow after each transaction.
3998 ········/// </summary>
3999 ········public virtual bool HollowMode
4000 ········{
4001 ············get { return hollowMode; }
4002 ············set { hollowMode = value; }
4003 ········}
4004
4005 ········internal TypeManager TypeManager
4006 ········{
4007 ············get { return typeManager; }
4008 ········}
4009
4010 ········/// <summary>
4011 ········/// Sets or gets transaction mode. Uses TransactionMode enum.
4012 ········/// </summary>
4013 ········/// <remarks>
4014 ········/// Set this value before you start any transactions.
4015 ········/// </remarks>
4016 ········public TransactionMode TransactionMode
4017 ········{
4018 ············get { return TransactionScope.TransactionMode; }
4019 ············set { TransactionScope.TransactionMode = value; }
4020 ········}
4021
4022 ········/// <summary>
4023 ········/// Sets or gets the Isolation Level.
4024 ········/// </summary>
4025 ········/// <remarks>
4026 ········/// Set this value before you start any transactions.
4027 ········/// </remarks>
4028 ········public IsolationLevel IsolationLevel
4029 ········{
4030 ············get { return TransactionScope.IsolationLevel; }
4031 ············set { TransactionScope.IsolationLevel = value; }
4032 ········}
4033
4034 ········internal class MappingTableEntry
4035 ········{
4036 ············private IPersistenceCapable parentObject;
4037 ············private IPersistenceCapable relatedObject;
4038 ············private Relation relation;
4039 ············private bool deleteEntry;
4040 ············
4041 ············public MappingTableEntry(IPersistenceCapable pc, IPersistenceCapable relObj, Relation r) : this(pc, relObj, r, false)
4042 ············{
4043 ············}
4044 ············
4045 ············public MappingTableEntry(IPersistenceCapable pc, IPersistenceCapable relObj, Relation r, bool deleteEntry)
4046 ············{
4047 ················parentObject = pc;
4048 ················relatedObject = relObj;
4049 ················relation = r;
4050 ················this.deleteEntry = deleteEntry;
4051 ············}
4052
4053 ············public bool DeleteEntry
4054 ············{
4055 ················get
4056 ················{
4057 ····················return deleteEntry;
4058 ················}
4059 ············}
4060
4061 ············public IPersistenceCapable ParentObject
4062 ············{
4063 ················get
4064 ················{
4065 ····················return parentObject;
4066 ················}
4067 ············}
4068
4069 ············public IPersistenceCapable RelatedObject
4070 ············{
4071 ················get
4072 ················{
4073 ····················return relatedObject;
4074 ················}
4075 ············}
4076
4077 ············public Relation Relation
4078 ············{
4079 ················get
4080 ················{
4081 ····················return relation;
4082 ················}
4083 ············}
4084 ········}
4085
4086 ········/// <summary>
4087 ········/// Get a DataRow representing the given object.
4088 ········/// </summary>
4089 ········/// <param name="o"></param>
4090 ········/// <returns></returns>
4091 ········public DataRow GetClonedDataRow( object o )
4092 ········{
4093 ············IPersistenceCapable pc = CheckPc( o );
4094
4095 ············if (pc.NDOObjectState == NDOObjectState.Deleted || pc.NDOObjectState == NDOObjectState.Transient)
4096 ················throw new Exception( "GetDataRow: State of the object must not be Deleted or Transient." );
4097
4098 ············DataRow row = cache.GetDataRow( pc );
4099 ············DataTable newTable = row.Table.Clone();
4100 ············newTable.ImportRow( row );
4101 ············row = newTable.Rows[0];
4102
4103 ············Class cls = mappings.FindClass(o.GetType());
4104 ············WriteObject( pc, row, cls.ColumnNames );
4105 ············WriteForeignKeysToRow( pc, row );
4106
4107 ············return row;
4108 ········}
4109
4110 ········/// <summary>
4111 ········/// Gets an object, which shows all changes applied to the given object.
4112 ········/// This function can be used to build an audit system.
4113 ········/// </summary>
4114 ········/// <param name="o"></param>
4115 ········/// <returns>An ExpandoObject</returns>
4116 ········public ChangeLog GetChangeSet( object o )
4117 ········{
4118 ············var changeLog = new ChangeLog(this);
4119 ············changeLog.Initialize( o );
4120 ············return changeLog;
4121 ········}
4122
4123 ········/// <summary>
4124 ········/// Outputs a revision number representing the assembly version.
4125 ········/// </summary>
4126 ········/// <remarks>This can be used for debugging purposes</remarks>
4127 ········public int Revision
4128 ········{
4129 ············get
4130 ············{
4131 ················Version v = new AssemblyName( GetType().Assembly.FullName ).Version;
4132 ················string vstring = String.Format( "{0}{1:D2}{2}{3:D2}", v.Major, v.Minor, v.Build, v.MinorRevision );
4133 ················return int.Parse( vstring );
4134 ············}
4135 ········}
4136 ····}
4137 }
4138