-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFastDAO.cs
1690 lines (1587 loc) · 79.2 KB
/
FastDAO.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2004-2010 Azavea, Inc.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Xml;
using Azavea.Open.Common;
using Azavea.Open.DAO.Criteria;
using Azavea.Open.DAO.Criteria.Grouping;
using Azavea.Open.DAO.Criteria.Joins;
using Azavea.Open.DAO.Exceptions;
using Azavea.Open.DAO.Util;
using log4net;
namespace Azavea.Open.DAO
{
/// <summary>
/// This class is built to be a "fast and easy" way of reading/writing objects to/from a
/// data source. It is meant to have high performance on throughput of large numbers of objects.
/// It does not support every possible sophistication that an ORM system can have.
/// </summary>
public class FastDAO<T> : IFastDaoInserter<T>, IFastDaoUpdater<T>, IFastDaoDeleter<T>, IFastDaoReader<T> where T : class, new()
{
/// <summary>
/// This is the value that will be returned from methods that return a number of rows
/// affected, if the number is unable to be determined.
/// </summary>
public const int UNKNOWN_NUM_ROWS = -123;
/// <summary>
/// log4net logger that any child class may use for logging any appropriate messages.
/// </summary>
protected ILog _log = LogManager.GetLogger(
new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().DeclaringType.Namespace);
/// <summary>
/// The connection descriptor created from the connection config parameters.
/// </summary>
private readonly IConnectionDescriptor _connDesc;
/// <summary>
/// The ClassMapping object representing the class-to-table mapping
/// loaded from the config file.
/// </summary>
protected readonly ClassMapping _classMap;
/// <summary>
/// The data access layer can be different depending on what kind of data source we're talking to.
/// </summary>
protected readonly IDaLayer _dataAccessLayer;
/// <summary>
/// The name of the table (or equivalent) in the data storage that this DAO reads/writes to/from.
/// </summary>
public string Table
{
get { return _classMap.Table; }
}
/// <summary>
/// The class mapping used to map this DAO's data object type to the data storage.
/// </summary>
public ClassMapping ClassMap
{
get { return _classMap; }
}
/// <summary>
/// The object describing how to connect to and/or interact with the data
/// source we're reading objects from.
/// </summary>
public IConnectionDescriptor ConnDesc
{
get { return _connDesc; }
}
/// <summary>
/// The lower-level object with more direct database access. You should only
/// ever use this if you're trying to do something complicated that the FastDAO
/// interface doesn't expose.
///
/// NOTE: Using this directly can be less efficient if you are not careful.
/// </summary>
public IDaLayer DataAccessLayer
{
get { return _dataAccessLayer; }
}
#region Constructors
/// <summary>
/// This allows you to specify the config name and the section in the config file
/// used to get the database config info.
/// </summary>
/// <param name="configName">Name used to get the configuration.</param>
/// <param name="sectionName">Name of the section within the config file.</param>
public FastDAO(string configName, string sectionName)
: this(Config.GetConfig(configName), sectionName, null)
{
}
/// <summary>
/// This allows you to specify the config name and the section in the config file
/// used to get the database config info.
/// </summary>
/// <param name="configName">Name used to get the configuration.</param>
/// <param name="sectionName">Name of the section within the config file.</param>
/// <param name="decryptionDelegate">The method to call to decrypt passwords or
/// other encrypted connection info. May be null.</param>
public FastDAO(string configName, string sectionName,
ConnectionInfoDecryptionDelegate decryptionDelegate)
: this(Config.GetConfig(configName), sectionName, decryptionDelegate)
{
}
/// <summary>
/// This allows you to give the config object and the section in the config
/// used to get the database config info.
/// </summary>
/// <param name="config">Configuration object (presumably read ahead of time).</param>
/// <param name="sectionName">Name of the section within the config.</param>
public FastDAO(Config config, string sectionName) : this(config, sectionName, null)
{
}
/// <summary>
/// This allows you to give the config object and the section in the config
/// used to get the database config info.
/// </summary>
/// <param name="config">Configuration object (presumably read ahead of time).</param>
/// <param name="sectionName">Name of the section within the config.</param>
/// <param name="decryptionDelegate">The method to call to decrypt passwords or
/// other encrypted connection info. May be null.</param>
public FastDAO(Config config, string sectionName,
ConnectionInfoDecryptionDelegate decryptionDelegate) :
this(ConnectionDescriptor.LoadFromConfig(config, sectionName, decryptionDelegate),
config.ParameterExists(sectionName, "MAPPING")
? ParseHibernateConfig(typeof(T), config.GetParameterWithSubstitution(sectionName, "MAPPING", false))
: ParseHibernateConfig(typeof(T), config.GetConfigXml(sectionName), config.ConfigFile))
{
}
/// <summary>
/// This allows you to specify the data source connection info and the mapping file.
/// </summary>
/// <param name="connDesc">DB Connection information.</param>
/// <param name="mappingFileName">Filename (with path) to the mapping file.</param>
public FastDAO(IConnectionDescriptor connDesc, string mappingFileName) :
this(connDesc, ParseHibernateConfig(typeof(T), mappingFileName))
{
}
/// <summary>
/// If you already have the DB connection and the mapping information, you may use
/// this constructor.
/// </summary>
/// <param name="connDesc">DB Connection information.</param>
/// <param name="mapping">ClassMapping describing the class to be mapped and
/// the table to map it to.</param>
public FastDAO(IConnectionDescriptor connDesc, ClassMapping mapping)
{
if (connDesc == null)
{
throw new ArgumentNullException("connDesc", "Connection descriptor must not be null.");
}
if (mapping == null)
{
throw new ArgumentNullException("mapping", "Class mapping must not be null.");
}
_connDesc = connDesc;
_dataAccessLayer = _connDesc.CreateDataAccessLayer();
_classMap = mapping;
}
/// <summary>
/// Loads ClassMappings from NHibernate config xml. This method is somewhat
/// fragile (doesn't catch exceptions), since if we can't parse the NHibernate
/// config, we can't do much. However it will ignore problems with class mappings
/// other than for the desired type.
///
/// Static so we can call it from the constructor.
/// </summary>
/// <param name="desiredType">The type we're loading a mapping for.</param>
/// <param name="fileName">XML File containing an NHibernate configuration.</param>
/// <returns>The class mapping for the desired type. If unable to find it, an
/// exception is thrown, so you may safely assume this will never return
/// null.</returns>
private static ClassMapping ParseHibernateConfig(Type desiredType, string fileName)
{
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
return ParseHibernateConfig(desiredType, doc, fileName);
}
/// <summary>
/// Loads ClassMappings from NHibernate config xml. This method is somewhat
/// fragile (doesn't catch exceptions), since if we can't parse the NHibernate
/// config, we can't do much. However it will ignore problems with class mappings
/// other than for the desired type.
///
/// Static so we can call it from the constructor.
/// </summary>
/// <param name="desiredType">The type we're loading a mapping for.</param>
/// <param name="xmlStr">The XML text that contains the NHibernate-style XML configuration.</param>
/// <param name="xmlSource">Where the XML came from, I.E. a filename or other explaination
/// you would like to see in an error message. Used only for exception
/// message, may be null.</param>
/// <returns>The class mapping for the desired type. If unable to find it, an
/// exception is thrown, so you may safely assume this will never return
/// null.</returns>
private static ClassMapping ParseHibernateConfig(Type desiredType, string xmlStr, string xmlSource)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
return ParseHibernateConfig(desiredType, doc, xmlSource);
}
/// <summary>
/// Loads ClassMappings from NHibernate config xml. This method is somewhat
/// fragile (doesn't catch exceptions), since if we can't parse the NHibernate
/// config, we can't do much. However it will ignore problems with class mappings
/// other than for the desired type.
///
/// Static so we can call it from the constructor.
/// </summary>
/// <param name="desiredType">The type we're loading a mapping for.</param>
/// <param name="xml">The XML node that contains the NHibernate-style XML configuration.</param>
/// <param name="xmlSource">Where the XML came from, I.E. a filename or other explaination
/// you would like to see in an error message. Used only for exception
/// message, may be null.</param>
/// <returns>The class mapping for the desired type. If unable to find it, an
/// exception is thrown, so you may safely assume this will never return
/// null.</returns>
private static ClassMapping ParseHibernateConfig(Type desiredType, XmlNode xml, string xmlSource)
{
ClassMapping retVal = null;
foreach (XmlNode node in GetClassNodes(xml))
{
string name = node.Attributes["name"].Value;
if (desiredType.Equals(Type.GetType(name)))
{
retVal = new ClassMapping(node);
break;
}
}
if (retVal == null)
{
throw new BadDaoConfigurationException("Type " + desiredType.FullName +
" does not appear to be mapped in " + xmlSource);
}
return retVal;
}
/// <summary>
/// After some experimentation, it was determined that using a manual recursive
/// function to find all the 'class' nodes is fastest, GetElementsByTagName is
/// almost 3x slower (and only works on XmlDocuments not XmlNodes anyway) and
/// SelectNodes is 2.5x slower than GetElementsByTagName.
/// </summary>
/// <param name="node">Top node of the tree where we're looking for class nodes.</param>
/// <returns>A list of all the class nodes in this xml tree.</returns>
private static IList<XmlNode> GetClassNodes(XmlNode node)
{
List<XmlNode> retVal = new List<XmlNode>();
WalkTreeForClassNodes(node, retVal);
return retVal;
}
private static void WalkTreeForClassNodes(XmlNode node, ICollection<XmlNode> putEmHere)
{
if (node.Name == "class")
{
putEmHere.Add(node);
}
else
{
foreach (XmlNode child in node)
{
WalkTreeForClassNodes(child, putEmHere);
}
}
}
#endregion
#region Methods For Modifying Behavior
/// <summary>
/// A method to add a coercion delegate for a type. This allows you to specify how
/// to convert an unsupported type to/from the data source.
/// </summary>
/// <param name="t">The type to coerce.</param>
/// <param name="coercionDelegate">How to coerce it.</param>
public void AddCoercibleType(Type t, TypeCoercionDelegate coercionDelegate)
{
_dataAccessLayer.AddCoercibleType(t, coercionDelegate);
}
#endregion
#region Delete
/// <summary>
/// Deletes the specified object from the data source.
/// </summary>
/// <param name="dataObject">An object to delete from the DB.</param>
public virtual void Delete(T dataObject)
{
Delete(null, dataObject);
}
/// <summary>
/// Deletes the specified object from the data source.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="dataObject">An object to delete from the DB.</param>
public virtual void Delete(ITransaction transaction, T dataObject)
{
if (_classMap.IdDataColsByObjAttrs.Count <= 0)
{
throw new BadDaoConfigurationException("You cannot delete an object of a type with no ID fields defined: " + typeof(T));
}
// Put all the IDs on the criteria.
DaoCriteria crit = DbCaches.Criteria.Get();
foreach (string propName in _classMap.IdDataColsByObjAttrs.Keys)
{
crit.Expressions.Add(new EqualExpression(propName, GetValueFromObject(dataObject, propName)));
}
int numRecs = _dataAccessLayer.Delete(transaction, _classMap, crit);
if ((numRecs != 1) && (numRecs != UNKNOWN_NUM_ROWS))
{
throw new UnexpectedResultsException("Delete statement deleted " + numRecs + " rows (should have been 1).",
_connDesc);
}
}
/// <summary>
/// Deletes the specified objects from the data source. If the objects are not in the
/// data source, it ignores them.
/// </summary>
public virtual void Delete(IEnumerable<T> deleteUs)
{
Delete(null, deleteUs);
}
/// <summary>
/// Deletes the specified objects from the data source. If the objects are not in the
/// data source, it ignores them.
/// </summary>
public virtual void Delete(ITransaction transaction, IEnumerable<T> deleteUs)
{
foreach (T obj in deleteUs)
{
Delete(transaction, obj);
}
}
/// <summary>
/// Deletes objects from the data source that meet the given criteria.
/// </summary>
/// <param name="crit">Criteria for deletion. NOTE: Only the expressions are observed,
/// other things (like "order" or start / limit) are ignored.
/// Also, null or blank (no expressions) criteria are NOT allowed.
/// If you really wish to delete everything, call DeleteAll().</param>
/// <returns>The number of rows/objects deleted (or UNKNOWN_NUM_ROWS).</returns>
public virtual int Delete(DaoCriteria crit)
{
return Delete(null, crit);
}
/// <summary>
/// Deletes objects from the data source that meet the given criteria.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="crit">Criteria for deletion. NOTE: Only the expressions are observed,
/// other things (like "order" or start / limit) are ignored.
/// Also, null or blank (no expressions) criteria are NOT allowed.
/// If you really wish to delete everything, call DeleteAll().</param>
/// <returns>The number of rows/objects deleted (or UNKNOWN_NUM_ROWS).</returns>
public virtual int Delete(ITransaction transaction, DaoCriteria crit)
{
if ((crit == null) || (crit.Expressions.Count == 0))
{
throw new ArgumentNullException("crit",
"Critera must be non-null and must contain at least one expression. To delete all records, use the DeleteAll method.");
}
return _dataAccessLayer.Delete(transaction, _classMap, crit);
}
/// <summary>
/// Deletes all records of this dao's type.
/// </summary>
/// <returns>The number of rows/objects deleted.</returns>
public virtual int DeleteAll()
{
return DeleteAll(null);
}
/// <summary>
/// Deletes all records of this dao's type.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <returns>The number of rows/objects deleted.</returns>
public virtual int DeleteAll(ITransaction transaction)
{
return _dataAccessLayer.Delete(transaction, _classMap, null);
}
/// <summary>
/// Deletes every row from the table for this DAO.
/// Performance will be equal to or better than DeleteAll, but may require
/// that the user (from the connection descriptor) have greater permissions
/// than necessary for DeleteAll. Depends on the implementation.
/// </summary>
public virtual void Truncate()
{
_log.Info("Truncating " + _classMap.Table);
_dataAccessLayer.Truncate(_classMap);
_log.Info("Finished truncating " + _classMap.Table);
}
#endregion
#region "Save" (Insert or Update as appropriate)
/// <summary>
/// Tries to update the object if it is already in the DB, which it guesses by calling
/// IsIDValid on it and/or by just trying tye update and seeing if it works, otherwise
/// inserts it as a new record.
///
/// NOTE: If you already know whether you're going to be doing an insert or an update,
/// calling Insert() or Update() will be faster.
/// </summary>
/// <param name="obj">The object to save.</param>
public void Save(T obj)
{
Save(obj, false);
}
/// <summary>
/// Overload for Save that allows us to put the generated ID into the object if inserting
/// to a table with a DB-generated ID column.
/// </summary>
/// <param name="obj"></param>
/// <param name="setGeneratedId">Whether to set the generated ID on the
/// object to be saved.</param>
public void Save(T obj, bool setGeneratedId)
{
// If it has a valid ID, it's probably already been saved so we should try and update.
if (IsIDValid(obj))
{
SaveRecord(null, obj, true, true, setGeneratedId);
}
else // otherwise, only try to insert.
{
SaveRecord(null, obj, false, true, setGeneratedId);
}
}
#endregion
#region Insert
/// <summary>
/// Faster than Save if you know this is a new object that is being inserted.
/// Inserts the object into the data source. If there are unique constraints on
/// the data source and this is a duplicate record, this may generate an error.
/// </summary>
/// <param name="obj">The object to save.</param>
/// <param name="setGeneratedId">Update the object with its new ID if the ID was
/// autogenerated by the database. That requires a
/// second DB query to retrieve the ID and "most" of the
/// time you may not need it.
/// If setGeneratedId is false, this ONLY Updates the
/// object's ID field(s) IF the mapping contains a sequence,
/// meaning that FastDAO must query the sequence for the next
/// value anyway.</param>
public void Insert(T obj, bool setGeneratedId)
{
Insert(null, obj, setGeneratedId);
}
/// <summary>
/// Faster than Save if you know this is a new object that is being inserted.
/// Inserts the object into the data source. If there are unique constraints on
/// the data source and this is a duplicate record, this may generate an error.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="obj">The object to save.</param>
/// <param name="setGeneratedId">Update the object with its new ID if the ID was
/// autogenerated by the database. That requires a
/// second DB query to retrieve the ID and "most" of the
/// time you may not need it.
/// If setGeneratedId is false, this ONLY Updates the
/// object's ID field(s) IF the mapping contains a sequence,
/// meaning that FastDAO must query the sequence for the next
/// value anyway.</param>
public void Insert(ITransaction transaction, T obj, bool setGeneratedId)
{
SaveRecord(transaction, obj, false, true, setGeneratedId);
}
/// <summary>
/// Simpler override, same as calling Insert(obj, false);
/// </summary>
/// <param name="obj">The object to save.</param>
public virtual void Insert(T obj)
{
Insert(null, obj, false);
}
/// <summary>
/// Simpler override, same as calling Insert(obj, false);
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="obj">The object to save.</param>
public virtual void Insert(ITransaction transaction, T obj)
{
Insert(transaction, obj, false);
}
/// <summary>
/// Inserts a bunch of records, hopefully to be faster than
/// separate calls to Insert(). Whether it is or not depends on the implementation.
/// </summary>
/// <param name="insertUs">List of objects to save.</param>
public virtual void Insert(IEnumerable<T> insertUs)
{
Insert(null, insertUs);
}
/// <summary>
/// Inserts a bunch of records, hopefully to be faster than
/// separate calls to Insert(). Whether it is or not depends on the implementation.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="insertUs">List of objects to save.</param>
public virtual void Insert(ITransaction transaction, IEnumerable<T> insertUs)
{
List<IDictionary<string, object>> propValueDictionaries = new List<IDictionary<string, object>>();
foreach (T obj in insertUs)
{
Dictionary<string, object> colsToWrite = DbCaches.StringObjectDicts.Get();
Dictionary<string, object> idCols = DbCaches.StringObjectDicts.Get();
GetFieldValues(obj, colsToWrite, _classMap, false, true);
GetFieldValues(obj, idCols, _classMap, true, false);
ProcessIdColumnsForInsert(obj, idCols, colsToWrite);
propValueDictionaries.Add(colsToWrite);
}
if (propValueDictionaries.Count > 0)
{
_dataAccessLayer.InsertBatch(transaction, _classMap, propValueDictionaries);
}
else
{
_log.Warn("InsertBatch was called without any objects in the collection.");
}
}
#endregion
#region Update
/// <summary>
/// Faster than Save if you know this is an existing object that is being updated.
/// Updates the data source with the new values from this object. May generate an
/// error if the object does not in fact exist in the data source yet.
/// </summary>
/// <param name="obj">The object to save.</param>
public virtual void Update(T obj)
{
Update(null, obj);
}
/// <summary>
/// Faster than Save if you know this is an existing object that is being updated.
/// Updates the data source with the new values from this object. May generate an
/// error if the object does not in fact exist in the data source yet.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="obj">The object to save.</param>
public virtual void Update(ITransaction transaction, T obj)
{
SaveRecord(transaction, obj, true, false, false);
}
/// <summary>
/// Updates a bunch of records, hopefully to be faster than
/// separate calls to Update(). Whether it is or not depends on the implementation.
/// </summary>
/// <param name="updateUs">List of objects to save.</param>
public virtual void Update(IEnumerable<T> updateUs)
{
Update(null, updateUs);
}
/// <summary>
/// Updates a bunch of records, hopefully to be faster than
/// separate calls to Update(). Whether it is or not depends on the implementation.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="updateUs">List of objects to save.</param>
public virtual void Update(ITransaction transaction, IEnumerable<T> updateUs)
{
List<DaoCriteria> criteriaList = new List<DaoCriteria>();
List<IDictionary<string, object>> propValueDictionaries = new List<IDictionary<string, object>>();
foreach (T obj in updateUs)
{
DaoCriteria idCrit = DbCaches.Criteria.Get();
Dictionary<string, object> colsToWrite = DbCaches.StringObjectDicts.Get();
GetFieldValues(obj, colsToWrite, _classMap, false, true);
PopulateIDCriteria(obj, idCrit, _classMap);
criteriaList.Add(idCrit);
propValueDictionaries.Add(colsToWrite);
}
if (criteriaList.Count > 0)
{
_dataAccessLayer.UpdateBatch(transaction, _classMap, criteriaList, propValueDictionaries);
}
else
{
_log.Warn("UpdateBatch was called without any objects in the collection.");
}
}
#endregion
#region Querying
/// <summary>
/// Returns all objects of the given type.
/// </summary>
/// <returns>A list of objects, or an empty list (not null).</returns>
public IList<T> Get()
{
return Get((ITransaction)null);
}
/// <summary>
/// Returns all objects of the given type.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <returns>A list of objects, or an empty list (not null).</returns>
public IList<T> Get(ITransaction transaction)
{
return Get(transaction, null);
}
/// <summary>
/// Queries for objects of the specified type where the property matches the given value.
/// </summary>
/// <param name="propName">Property or Field on the object you want to match a value.</param>
/// <param name="val">Value that the Property or Field should have.</param>
/// <returns>The first object that matches the criteria.</returns>
public T GetFirst(string propName, object val)
{
return GetFirst(null, propName, val);
}
/// <summary>
/// Queries for objects of the specified type where the property matches the given value.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="propName">Property or Field on the object you want to match a value.</param>
/// <param name="val">Value that the Property or Field should have.</param>
/// <returns>The first object that matches the criteria.</returns>
public T GetFirst(ITransaction transaction, string propName, object val)
{
DaoCriteria crit = DbCaches.Criteria.Get();
try
{
crit.Expressions.Add(new EqualExpression(propName, val, true));
return GetFirst(transaction, crit);
}
finally
{
DbCaches.Criteria.Return(crit);
}
}
/// <summary>
/// Queries for one object that matches the given criteria.
/// </summary>
/// <returns>The first object that matches the criteria.</returns>
public T GetFirst(DaoCriteria crit)
{
// To speed this up, we'll set the limit to one.
int oldLimit = crit.Limit;
try
{
crit.Limit = 1;
IList<T> list = Get(crit);
T retVal;
if (list == null || list.Count < 1)
{
// This means null if it's an object.
retVal = default(T);
}
else
{
retVal = list[0];
}
return retVal;
}
finally
{
crit.Limit = oldLimit;
}
}
/// <summary>
/// Queries for one object that matches the given criteria.
/// </summary>
/// <returns>The first object that matches the criteria.</returns>
public T GetFirst(ITransaction transaction, DaoCriteria crit)
{
// To speed this up, we'll set the limit to one.
int oldLimit = crit.Limit;
try
{
crit.Limit = 1;
IList<T> list = Get(transaction, crit);
T retVal;
if (list == null || list.Count < 1)
{
// This means null if it's an object.
retVal = default(T);
}
else
{
retVal = list[0];
}
return retVal;
}
finally
{
crit.Limit = oldLimit;
}
}
/// <summary>
/// Queries for objects where the property matches the given value.
/// </summary>
/// <param name="propertyName">Property or Field on the object you want to match a value.</param>
/// <param name="propertyValue">Value that the Property or Field should have.</param>
/// <returns>All objects that match the criteria, or an empty list (not null).</returns>
public IList<T> Get(string propertyName, object propertyValue)
{
return Get(null, propertyName, propertyValue);
}
/// <summary>
/// Queries for objects where the property matches the given value.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="propertyName">Property or Field on the object you want to match a value.</param>
/// <param name="propertyValue">Value that the Property or Field should have.</param>
/// <returns>All objects that match the criteria, or an empty list (not null).</returns>
public IList<T> Get(ITransaction transaction, string propertyName, object propertyValue)
{
DaoCriteria crit = DbCaches.Criteria.Get();
try
{
crit.Expressions.Add(new EqualExpression(propertyName, propertyValue, true));
return Get(transaction, crit);
}
finally
{
DbCaches.Criteria.Return(crit);
}
}
/// <summary>
/// Queries and returns objects matching the criteria.
/// </summary>
/// <returns>A list of objects, or an empty list (not null).</returns>
public virtual IList<T> Get(DaoCriteria crit)
{
Hashtable parameters = DbCaches.Hashtables.Get();
if (crit != null)
{
if (crit.Start > 0)
{
parameters.Add("start", crit.Start);
}
if (crit.Limit > 0)
{
parameters.Add("limit", crit.Limit);
}
}
IDaQuery query = _dataAccessLayer.CreateQuery(_classMap, crit);
_dataAccessLayer.ExecuteQuery(null, _classMap, query, CreateObjectsFromReader, parameters);
_dataAccessLayer.DisposeOfQuery(query);
IList<T> items = (IList<T>)parameters["items"];
DbCaches.Hashtables.Return(parameters);
return items;
}
/// <summary>
/// Queries and returns objects matching the criteria.
/// </summary>
/// <returns>A list of objects, or an empty list (not null).</returns>
public virtual IList<T> Get(ITransaction transaction, DaoCriteria crit)
{
Hashtable parameters = DbCaches.Hashtables.Get();
if (crit != null)
{
if (crit.Start > 0)
{
parameters.Add("start", crit.Start);
}
if (crit.Limit > 0)
{
parameters.Add("limit", crit.Limit);
}
}
IDaQuery query = _dataAccessLayer.CreateQuery(_classMap, crit);
_dataAccessLayer.ExecuteQuery(transaction, _classMap, query, CreateObjectsFromReader, parameters);
_dataAccessLayer.DisposeOfQuery(query);
IList<T> items = (IList<T>)parameters["items"];
DbCaches.Hashtables.Return(parameters);
return items;
}
/// <summary>
/// Returns the number of objects matching the given criteria.
/// </summary>
public virtual int GetCount(DaoCriteria crit)
{
return GetCount(null, crit);
}
/// <summary>
/// Returns the number of objects matching the given criteria.
/// </summary>
public virtual int GetCount(ITransaction transaction, DaoCriteria crit)
{
return _dataAccessLayer.GetCount(transaction, _classMap, crit);
}
/// <summary>
/// Returns the number of objects of the specified type matching the given criteria,
/// aggregated by the given grouping expressions. This matches "GROUP BY" behavior
/// in SQL.
/// </summary>
/// <param name="crit">The criteria that you wish the objects to match. Start/limit and order are ignored.</param>
/// <param name="groupExpressions">The fields/expressions to aggregate on when counting.</param>
/// <returns>The number of objects that match the criteria.</returns>
public virtual List<GroupCountResult> GetCount(DaoCriteria crit, ICollection<AbstractGroupExpression> groupExpressions)
{
return GetCount(null, crit, groupExpressions);
}
/// <summary>
/// Returns the number of objects of the specified type matching the given criteria,
/// aggregated by the given grouping expressions. This matches "GROUP BY" behavior
/// in SQL.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="crit">The criteria that you wish the objects to match. Start/limit and order are ignored.</param>
/// <param name="groupExpressions">The fields/expressions to aggregate on when counting.</param>
/// <returns>The number of objects that match the criteria.</returns>
public virtual List<GroupCountResult> GetCount(ITransaction transaction, DaoCriteria crit, ICollection<AbstractGroupExpression> groupExpressions)
{
return _dataAccessLayer.GetCount(transaction, _classMap, crit, groupExpressions);
}
/// <summary>
/// Queries for objects, similar to Get, except that this iterates over the resulting
/// records and invokes the specified delegate for each one. This allows processing of much
/// larger result sets since it doesn't attempt to load all the objects into memory at once.
/// </summary>
/// <param name="criteria">Any criteria for the query. May be null for "all records".</param>
/// <param name="invokeMe">The method to invoke for each object returned by the query.</param>
/// <param name="parameters">Any parameters that you want to pass to the invokeMe method.
/// This may be null.</param>
/// <param name="desc">Description of the loop for logging purposes.</param>
/// <returns>The number of objects iterated over.</returns>
public int Iterate<P>(DaoCriteria criteria, DaoIterationDelegate<T, P> invokeMe,
P parameters, string desc)
{
return Iterate(null, criteria, invokeMe, parameters, desc);
}
/// <summary>
/// Queries for objects, similar to Get, except that this iterates over the resulting
/// records and invokes the specified delegate for each one. This allows processing of much
/// larger result sets since it doesn't attempt to load all the objects into memory at once.
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="criteria">Any criteria for the query. May be null for "all records".</param>
/// <param name="invokeMe">The method to invoke for each object returned by the query.</param>
/// <param name="parameters">Any parameters that you want to pass to the invokeMe method.
/// This may be null.</param>
/// <param name="desc">Description of the loop for logging purposes.</param>
/// <returns>The number of objects iterated over.</returns>
public int Iterate<P>(ITransaction transaction, DaoCriteria criteria, DaoIterationDelegate<T, P> invokeMe,
P parameters, string desc)
{
int limit = (criteria == null || criteria.Limit <= 0) ? int.MaxValue : criteria.Limit;
IDaQuery query = _dataAccessLayer.CreateQuery(_classMap, criteria);
int retVal = IterateOverQuery(transaction, query, invokeMe, parameters, limit, desc);
_dataAccessLayer.DisposeOfQuery(query);
return retVal;
}
#endregion
#region Join Support
/// <summary>
/// This allows joining between two DAOs. Assuming both are using the same data
/// source, and joins are implemented in the data access layer, this will use
/// native joins (I.E. JOIN keyword in SQL) and be fast. If not, this will use
/// the "PseudoJoiner", and be less fast (though not horrible most of the time,
/// depending on the number of records and the data sources involved).
/// </summary>
/// <param name="crit">An object describing how to join the two DAOs. Includes any
/// criteria that apply to the right or left DAO.</param>
/// <param name="rightDao">The other DAO we are joining against.</param>
/// <typeparam name="R">The type of object returned by the other DAO.</typeparam>
/// <returns>A list of KeyValuePairs. The Key is the object from this </returns>
public List<JoinResult<T,R>> Get<R>(DaoJoinCriteria crit, IFastDaoReader<R> rightDao) where R : class, new()
{
return Get(null, crit, rightDao);
}
/// <summary>
/// This allows joining between two DAOs. Assuming both are using the same data
/// source, and joins are implemented in the data access layer, this will use
/// native joins (I.E. JOIN keyword in SQL) and be fast. If not, this will use
/// the "PseudoJoiner", and be less fast (though not horrible most of the time,
/// depending on the number of records and the data sources involved).
/// </summary>
/// <param name="transaction">The transaction to do this as part of. May be null.</param>
/// <param name="crit">An object describing how to join the two DAOs. Includes any
/// criteria that apply to the right or left DAO.</param>
/// <param name="rightDao">The other DAO we are joining against.</param>
/// <typeparam name="R">The type of object returned by the other DAO.</typeparam>
/// <returns>A list of KeyValuePairs. The Key is the object from this </returns>
public List<JoinResult<T, R>> Get<R>(ITransaction transaction, DaoJoinCriteria crit, IFastDaoReader<R> rightDao) where R : class, new()
{
// If the two DAOs use the same connection descriptor, and the data
// access layer supports joins, we can do an actual join via the
// data source. Otherwise, we'll fake it by querying first this
// DAO then the other DAO.
if ((_dataAccessLayer is IDaJoinableLayer) &&
((IDaJoinableLayer)_dataAccessLayer).CanJoin<R>(crit, rightDao.ConnDesc, rightDao.ClassMap))
{
Hashtable parameters = DbCaches.Hashtables.Get();
if (crit != null)
{
if (crit.Start > 0)
{
parameters.Add("start", crit.Start);
}
if (crit.Limit > 0)
{
parameters.Add("limit", crit.Limit);
}
}
parameters["rightDao"] = rightDao;
IDaJoinQuery query = ((IDaJoinableLayer)_dataAccessLayer).CreateJoinQuery(crit,
_classMap, rightDao.ClassMap);
parameters["leftPrefix"] = query.GetLeftColumnPrefix();
parameters["rightPrefix"] = query.GetRightColumnPrefix();
_dataAccessLayer.ExecuteQuery(transaction, _classMap, query,
CreateJoinObjectsFromReader<R>, parameters);
_dataAccessLayer.DisposeOfQuery(query);
List<JoinResult<T, R>> items = (List<JoinResult<T, R>>)parameters["items"];
DbCaches.Hashtables.Return(parameters);
return items;
}
return PseudoJoiner.Join(crit, this, rightDao);
}
/// <summary>
/// Performs a join using the given join criteria and returns the number of objects that
/// would result from the join if you called Get.
///
/// Whether this is faster than calling Get depends on the implementation.
/// </summary>