-
Notifications
You must be signed in to change notification settings - Fork 935
/
Copy pathConfiguration.cs
2554 lines (2302 loc) · 84.9 KB
/
Configuration.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using NHibernate.Bytecode;
using NHibernate.Cfg.ConfigurationSchema;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Cfg.XmlHbmBinding;
using NHibernate.Dialect;
using NHibernate.Dialect.Function;
using NHibernate.Dialect.Schema;
using NHibernate.Engine;
using NHibernate.Event;
using NHibernate.Id;
using NHibernate.Impl;
using NHibernate.Mapping;
using NHibernate.Proxy;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Type;
using NHibernate.Util;
using Array = System.Array;
namespace NHibernate.Cfg
{
/// <summary>
/// Allows the application to specify properties and mapping documents to be used when creating
/// a <see cref="ISessionFactory" />.
/// </summary>
/// <remarks>
/// <para>
/// Usually an application will create a single <see cref="Configuration" />, build a single instance
/// of <see cref="ISessionFactory" />, and then instantiate <see cref="ISession"/> objects in threads
/// servicing client requests.
/// </para>
/// <para>
/// The <see cref="Configuration" /> is meant only as an initialization-time object. <see cref="ISessionFactory" />
/// is immutable and does not retain any association back to the <see cref="Configuration" />
/// </para>
/// </remarks>
[Serializable]
public partial class Configuration : ISerializable
{
/// <summary>Default name for hibernate configuration file.</summary>
public const string DefaultHibernateCfgFileName = "hibernate.cfg.xml";
private string currentDocumentName;
private bool preMappingBuildProcessed;
protected IDictionary<string, PersistentClass> classes; // entityName, PersistentClass
protected IDictionary<string, NHibernate.Mapping.Collection> collections;
protected IDictionary<string, Table> tables;
protected IList<SecondPassCommand> secondPasses;
protected Queue<FilterSecondPassArgs> filtersSecondPasses;
protected IList<Mappings.PropertyReference> propertyReferences;
private IInterceptor interceptor;
private IDictionary<string, string> properties;
protected IList<IAuxiliaryDatabaseObject> auxiliaryDatabaseObjects;
private INamingStrategy namingStrategy = DefaultNamingStrategy.Instance;
private MappingsQueue mappingsQueue;
private EventListeners eventListeners;
protected IDictionary<string, TypeDef> typeDefs;
protected ISet<ExtendsQueueEntry> extendsQueue;
protected IDictionary<string, Mappings.TableDescription> tableNameBinding;
protected IDictionary<Table, Mappings.ColumnNames> columnNameBindingPerTable;
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(Configuration));
protected internal SettingsFactory settingsFactory;
#region ISerializable Members
public Configuration(SerializationInfo info, StreamingContext context)
{
Reset();
EntityNotFoundDelegate = GetSerialedObject<IEntityNotFoundDelegate>(info, "entityNotFoundDelegate");
auxiliaryDatabaseObjects = GetSerialedObject<IList<IAuxiliaryDatabaseObject>>(info, "auxiliaryDatabaseObjects");
classes = GetSerialedObject<IDictionary<string, PersistentClass>>(info, "classes");
collections = GetSerialedObject<IDictionary<string, NHibernate.Mapping.Collection>>(info, "collections");
columnNameBindingPerTable = GetSerialedObject<IDictionary<Table, Mappings.ColumnNames>>(info,
"columnNameBindingPerTable");
defaultAssembly = GetSerialedObject<string>(info, "defaultAssembly");
defaultNamespace = GetSerialedObject<string>(info, "defaultNamespace");
eventListeners = GetSerialedObject<EventListeners>(info, "eventListeners");
//this.extendsQueue = GetSerialedObject<ISet<ExtendsQueueEntry>>(info, "extendsQueue");
FilterDefinitions = GetSerialedObject<IDictionary<string, FilterDefinition>>(info, "filterDefinitions");
Imports = GetSerialedObject<IDictionary<string, string>>(info, "imports");
interceptor = GetSerialedObject<IInterceptor>(info, "interceptor");
mapping = GetSerialedObject<IMapping>(info, "mapping");
NamedQueries = GetSerialedObject<IDictionary<string, NamedQueryDefinition>>(info, "namedQueries");
NamedSQLQueries = GetSerialedObject<IDictionary<string, NamedSQLQueryDefinition>>(info, "namedSqlQueries");
namingStrategy = GetSerialedObject<INamingStrategy>(info, "namingStrategy");
properties = GetSerialedObject<IDictionary<string, string>>(info, "properties");
propertyReferences = GetSerialedObject<IList<Mappings.PropertyReference>>(info, "propertyReferences");
settingsFactory = GetSerialedObject<SettingsFactory>(info, "settingsFactory");
SqlFunctions = GetSerialedObject<IDictionary<string, ISQLFunction>>(info, "sqlFunctions");
SqlResultSetMappings = GetSerialedObject<IDictionary<string, ResultSetMappingDefinition>>(info,
"sqlResultSetMappings");
tableNameBinding = GetSerialedObject<IDictionary<string, Mappings.TableDescription>>(info, "tableNameBinding");
tables = GetSerialedObject<IDictionary<string, Table>>(info, "tables");
typeDefs = GetSerialedObject<IDictionary<string, TypeDef>>(info, "typeDefs");
filtersSecondPasses = GetSerialedObject<Queue<FilterSecondPassArgs>>(info, "filtersSecondPasses");
}
private T GetSerialedObject<T>(SerializationInfo info, string name)
{
return (T) info.GetValue(name, typeof(T));
}
[SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
ConfigureProxyFactoryFactory();
SecondPassCompile();
Validate();
info.AddValue("entityNotFoundDelegate", EntityNotFoundDelegate);
info.AddValue("auxiliaryDatabaseObjects", auxiliaryDatabaseObjects);
info.AddValue("classes", classes);
info.AddValue("collections", collections);
info.AddValue("columnNameBindingPerTable", columnNameBindingPerTable);
info.AddValue("defaultAssembly", defaultAssembly);
info.AddValue("defaultNamespace", defaultNamespace);
info.AddValue("eventListeners", eventListeners);
//info.AddValue("extendsQueue", this.extendsQueue);
info.AddValue("filterDefinitions", FilterDefinitions);
info.AddValue("imports", Imports);
info.AddValue("interceptor", interceptor);
info.AddValue("mapping", mapping);
info.AddValue("namedQueries", NamedQueries);
info.AddValue("namedSqlQueries", NamedSQLQueries);
info.AddValue("namingStrategy", namingStrategy);
info.AddValue("properties", properties);
info.AddValue("propertyReferences", propertyReferences);
info.AddValue("settingsFactory", settingsFactory);
info.AddValue("sqlFunctions", SqlFunctions);
info.AddValue("sqlResultSetMappings", SqlResultSetMappings);
info.AddValue("tableNameBinding", tableNameBinding);
info.AddValue("tables", tables);
info.AddValue("typeDefs", typeDefs);
info.AddValue("filtersSecondPasses", filtersSecondPasses);
}
#endregion
/// <summary>
/// Clear the internal state of the <see cref="Configuration"/> object.
/// </summary>
protected void Reset()
{
classes = new Dictionary<string, PersistentClass>(); //new SequencedHashMap(); - to make NH-369 bug deterministic
Imports = new Dictionary<string, string>();
collections = new Dictionary<string, NHibernate.Mapping.Collection>();
tables = new Dictionary<string, Table>();
NamedQueries = new Dictionary<string, NamedQueryDefinition>();
NamedSQLQueries = new Dictionary<string, NamedSQLQueryDefinition>();
SqlResultSetMappings = new Dictionary<string, ResultSetMappingDefinition>();
secondPasses = new List<SecondPassCommand>();
propertyReferences = new List<Mappings.PropertyReference>();
FilterDefinitions = new Dictionary<string, FilterDefinition>();
interceptor = EmptyInterceptor.Instance;
#pragma warning disable 618
properties = Environment.Properties;
#pragma warning restore 618
auxiliaryDatabaseObjects = new List<IAuxiliaryDatabaseObject>();
SqlFunctions = new Dictionary<string, ISQLFunction>();
mappingsQueue = new MappingsQueue();
eventListeners = new EventListeners();
typeDefs = new Dictionary<string, TypeDef>();
extendsQueue = new HashSet<ExtendsQueueEntry>();
tableNameBinding = new Dictionary<string, Mappings.TableDescription>();
columnNameBindingPerTable = new Dictionary<Table, Mappings.ColumnNames>();
filtersSecondPasses = new Queue<FilterSecondPassArgs>();
}
[Serializable]
private class Mapping : IMapping
{
private readonly Configuration configuration;
public Mapping(Configuration configuration)
{
this.configuration = configuration;
}
private PersistentClass GetPersistentClass(string className)
{
PersistentClass pc;
if (!configuration.classes.TryGetValue(className, out pc))
{
throw new MappingException("persistent class not known: " + className);
}
return pc;
}
public IType GetIdentifierType(string className)
{
return GetPersistentClass(className).Identifier.Type;
}
public string GetIdentifierPropertyName(string className)
{
PersistentClass pc = GetPersistentClass(className);
if (!pc.HasIdentifierProperty)
{
return null;
}
return pc.IdentifierProperty.Name;
}
public IType GetReferencedPropertyType(string className, string propertyName)
{
PersistentClass pc = GetPersistentClass(className);
Property prop = pc.GetReferencedProperty(propertyName);
if (prop == null)
{
throw new MappingException("property not known: " + pc.MappedClass.FullName + '.' + propertyName);
}
return prop.Type;
}
public bool HasNonIdentifierPropertyNamedId(string className)
{
return "id".Equals(GetIdentifierPropertyName(className));
}
public Dialect.Dialect Dialect =>
NHibernate.Dialect.Dialect.GetDialect(configuration.Properties);
}
[Serializable]
private class StaticDialectMappingWrapper : IMapping
{
private readonly IMapping _mapping;
public StaticDialectMappingWrapper(IMapping mapping): this(mapping, mapping.Dialect)
{
}
public StaticDialectMappingWrapper(IMapping mapping, Dialect.Dialect dialect)
{
_mapping = mapping;
Dialect = dialect;
}
public IType GetIdentifierType(string className)
{
return _mapping.GetIdentifierType(className);
}
public string GetIdentifierPropertyName(string className)
{
return _mapping.GetIdentifierPropertyName(className);
}
public IType GetReferencedPropertyType(string className, string propertyName)
{
return _mapping.GetReferencedPropertyType(className, propertyName);
}
public bool HasNonIdentifierPropertyNamedId(string className)
{
return _mapping.HasNonIdentifierPropertyNamedId(className);
}
public Dialect.Dialect Dialect { get; }
}
private IMapping mapping;
protected Configuration(SettingsFactory settingsFactory)
{
InitBlock();
this.settingsFactory = settingsFactory;
Reset();
}
private void InitBlock()
{
mapping = BuildMapping();
}
public virtual IMapping BuildMapping()
{
return new Mapping(this);
}
/// <summary>
/// Create a new Configuration object.
/// </summary>
public Configuration() : this(new SettingsFactory()) { }
/// <summary>
/// The class mappings
/// </summary>
public ICollection<PersistentClass> ClassMappings
{
get { return classes.Values; }
}
/// <summary>
/// The collection mappings
/// </summary>
public ICollection<NHibernate.Mapping.Collection> CollectionMappings
{
get { return collections.Values; }
}
/// <summary>
/// The table mappings
/// </summary>
private ICollection<Table> TableMappings
{
get { return tables.Values; }
}
/// <summary>
/// Get the mapping for a particular class
/// </summary>
public PersistentClass GetClassMapping(System.Type persistentClass)
{
// TODO NH: Remove this method
return GetClassMapping(persistentClass.FullName);
}
/// <summary> Get the mapping for a particular entity </summary>
/// <param name="entityName">An entity name. </param>
/// <returns> the entity mapping information </returns>
public PersistentClass GetClassMapping(string entityName)
{
PersistentClass result;
classes.TryGetValue(entityName, out result);
return result;
}
/// <summary>
/// Get the mapping for a particular collection role
/// </summary>
/// <param name="role">a collection role</param>
/// <returns><see cref="NHibernate.Mapping.Collection" /></returns>
public NHibernate.Mapping.Collection GetCollectionMapping(string role)
{
NHibernate.Mapping.Collection result;
collections.TryGetValue(role, out result);
return result;
}
/// <summary>
/// Read mappings from a particular XML file. This method is equivalent
/// to <see cref="AddXmlFile(string)" />.
/// </summary>
/// <param name="xmlFile"></param>
/// <returns></returns>
public Configuration AddFile(string xmlFile)
{
return AddXmlFile(xmlFile);
}
public Configuration AddFile(FileInfo xmlFile)
{
return AddFile(xmlFile.FullName);
}
private static void LogAndThrow(Exception exception)
{
if (log.IsErrorEnabled())
{
log.Error(exception, exception.Message);
}
throw exception;
}
/// <summary>
/// Read mappings from a particular XML file.
/// </summary>
/// <param name="xmlFile">a path to a file</param>
/// <returns>This configuration object.</returns>
public Configuration AddXmlFile(string xmlFile)
{
log.Info("Mapping file: {0}", xmlFile);
XmlTextReader textReader = null;
try
{
textReader = new XmlTextReader(xmlFile);
AddXmlReader(textReader, xmlFile);
}
catch (MappingException)
{
throw;
}
catch (Exception e)
{
LogAndThrow(new MappingException("Could not configure datastore from file " + xmlFile, e));
}
finally
{
if (textReader != null)
{
textReader.Close();
}
}
return this;
}
public Configuration AddXml(string xml)
{
return AddXml(xml, "(string)");
}
/// <summary>
/// Read mappings from a <see cref="string" />. This method is equivalent to
/// <see cref="AddXmlString(string)" />.
/// </summary>
/// <param name="xml">an XML string</param>
/// <param name="name">The name to use in error reporting. May be <see langword="null" />.</param>
/// <returns>This configuration object.</returns>
public Configuration AddXml(string xml, string name)
{
if (log.IsDebugEnabled())
{
log.Debug("Mapping XML:\n{0}", xml);
}
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(xml, XmlNodeType.Document, null);
// make a StringReader for the string passed in - the StringReader
// inherits from TextReader. We can use the XmlTextReader.ctor that
// takes the TextReader to build from a string...
AddXmlReader(reader, name);
}
catch (MappingException)
{
throw;
}
catch (Exception e)
{
LogAndThrow(new MappingException("Could not configure datastore from XML string " + name, e));
}
finally
{
if (reader != null)
{
reader.Close();
}
}
return this;
}
/// <summary>
/// Read mappings from a <see cref="string" />.
/// </summary>
/// <param name="xml">an XML string</param>
/// <returns>This configuration object.</returns>
public Configuration AddXmlString(string xml)
{
return AddXml(xml);
}
/// <summary>
/// Read mappings from a URL.
/// </summary>
/// <param name="url">a URL</param>
/// <returns>This configuration object.</returns>
public Configuration AddUrl(string url)
{
// AddFile works for URLs currently
return AddFile(url);
}
/// <summary>
/// Read mappings from a URL.
/// </summary>
/// <param name="url">a <see cref="Uri" /> to read the mappings from.</param>
/// <returns>This configuration object.</returns>
public Configuration AddUrl(Uri url)
{
return AddUrl(url.AbsolutePath);
}
public Configuration AddDocument(XmlDocument doc)
{
return AddDocument(doc, "(XmlDocument)");
}
/// <summary>
/// Read mappings from an <see cref="XmlDocument" />.
/// </summary>
/// <param name="doc">A loaded <see cref="XmlDocument" /> that contains the mappings.</param>
/// <param name="name">The name of the document, for error reporting purposes.</param>
/// <returns>This configuration object.</returns>
public Configuration AddDocument(XmlDocument doc, string name)
{
if (log.IsDebugEnabled())
{
log.Debug("Mapping XML:\n{0}", doc.OuterXml);
}
try
{
using (var ms = new MemoryStream())
{
doc.Save(ms);
ms.Position = 0;
AddInputStream(ms, name);
}
return this;
}
catch (MappingException)
{
throw;
}
catch (Exception e)
{
LogAndThrow(new MappingException("Could not configure datastore from XML document " + name, e));
return this; // To please the compiler
}
}
/// <summary>
/// Takes the validated XmlDocument and has the Binder do its work of
/// creating Mapping objects from the Mapping Xml.
/// </summary>
/// <param name="doc">The NamedXmlDocument that contains the <b>validated</b> mapping XML file.</param>
private void AddValidatedDocument(NamedXmlDocument doc)
{
AddDeserializedMapping(doc.Document, doc.Name);
}
public event EventHandler<BindMappingEventArgs> BeforeBindMapping;
public event EventHandler<BindMappingEventArgs> AfterBindMapping;
/// <summary>
/// Add mapping data using deserialized class.
/// </summary>
/// <param name="mappingDocument">Mapping metadata.</param>
/// <param name="documentFileName">XML file's name where available; otherwise null.</param>
public void AddDeserializedMapping(HbmMapping mappingDocument, string documentFileName)
{
if (mappingDocument == null)
{
throw new ArgumentNullException("mappingDocument");
}
try
{
var dialect = new Lazy<Dialect.Dialect>(() => Dialect.Dialect.GetDialect(properties));
OnBeforeBindMapping(new BindMappingEventArgs(mappingDocument, documentFileName) {LazyDialect = dialect});
var mappings = CreateMappings();
mappings.LazyDialect = dialect;
new MappingRootBinder(mappings).Bind(mappingDocument);
OnAfterBindMapping(new BindMappingEventArgs(mappingDocument, documentFileName) {LazyDialect = dialect});
}
catch (Exception e)
{
var message = documentFileName == null
? "Could not compile deserialized mapping document."
: "Could not compile the mapping document: " + documentFileName;
LogAndThrow(new MappingException(message, e));
}
}
public void AddMapping(HbmMapping mappingDocument)
{
AddDeserializedMapping(mappingDocument, "mapping_by_code");
}
private void OnAfterBindMapping(BindMappingEventArgs bindMappingEventArgs)
{
var handler = AfterBindMapping;
if (handler != null)
{
handler(this, bindMappingEventArgs);
}
}
private void OnBeforeBindMapping(BindMappingEventArgs bindMappingEventArgs)
{
var handler = BeforeBindMapping;
if (handler != null)
{
handler(this, bindMappingEventArgs);
}
}
/// <summary>
/// Create a new <see cref="Mappings" /> to add classes and collection
/// mappings to.
/// </summary>
//Since v5.2
[Obsolete("Please use overload without a dialect parameter.")]
public Mappings CreateMappings(Dialect.Dialect dialect)
{
var mappings = CreateMappings();
mappings.LazyDialect = new Lazy<Dialect.Dialect>(() => dialect);
return mappings;
}
public Mappings CreateMappings()
{
string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null);
string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null);
string preferPooledValuesLo = PropertiesHelper.GetString(Environment.PreferPooledValuesLo, properties, null);
ProcessPreMappingBuildProperties();
return new Mappings(classes, collections, tables, NamedQueries, NamedSQLQueries, SqlResultSetMappings, Imports,
secondPasses, filtersSecondPasses, propertyReferences, namingStrategy, typeDefs, FilterDefinitions, extendsQueue,
auxiliaryDatabaseObjects, tableNameBinding, columnNameBindingPerTable, defaultAssembly,
defaultNamespace, defaultCatalog, defaultSchema, preferPooledValuesLo);
}
private void ProcessPreMappingBuildProperties()
{
if (preMappingBuildProcessed)
{
return;
}
ConfigureCollectionTypeFactory();
preMappingBuildProcessed = true;
}
private void ConfigureCollectionTypeFactory()
{
var ctfc = GetProperty(Environment.CollectionTypeFactoryClass);
if (string.IsNullOrEmpty(ctfc))
{
return;
}
var ictfc = Environment.BytecodeProvider as IInjectableCollectionTypeFactoryClass;
if (ictfc == null)
{
return;
}
ictfc.SetCollectionTypeFactoryClass(ctfc);
}
/// <summary>
/// Read mappings from a <see cref="Stream" />.
/// </summary>
/// <param name="xmlInputStream">The stream containing XML</param>
/// <returns>This Configuration object.</returns>
/// <remarks>
/// The <see cref="Stream"/> passed in through the parameter <paramref name="xmlInputStream" />
/// is not <em>guaranteed</em> to be cleaned up by this method. It is the caller's responsiblity to
/// ensure that <paramref name="xmlInputStream" /> is properly handled when this method
/// completes.
/// </remarks>
public Configuration AddInputStream(Stream xmlInputStream)
{
return AddInputStream(xmlInputStream, null);
}
/// <summary>
/// Read mappings from a <see cref="Stream" />.
/// </summary>
/// <param name="xmlInputStream">The stream containing XML</param>
/// <param name="name">The name of the stream to use in error reporting. May be <see langword="null" />.</param>
/// <returns>This Configuration object.</returns>
/// <remarks>
/// The <see cref="Stream"/> passed in through the parameter <paramref name="xmlInputStream" />
/// is not <em>guaranteed</em> to be cleaned up by this method. It is the caller's responsiblity to
/// ensure that <paramref name="xmlInputStream" /> is properly handled when this method
/// completes.
/// </remarks>
public Configuration AddInputStream(Stream xmlInputStream, string name)
{
XmlTextReader textReader = null;
try
{
textReader = new XmlTextReader(xmlInputStream);
AddXmlReader(textReader, name);
return this;
}
catch (MappingException)
{
throw;
}
catch (Exception e)
{
LogAndThrow(new MappingException("Could not configure datastore from input stream " + name, e));
return this; // To please the compiler
}
finally
{
if (textReader != null)
{
textReader.Close();
}
}
}
/// <summary>
/// Adds the mappings in the resource of the assembly.
/// </summary>
/// <param name="path">The path to the resource file in the assembly.</param>
/// <param name="assembly">The assembly that contains the resource file.</param>
/// <returns>This configuration object.</returns>
public Configuration AddResource(string path, Assembly assembly)
{
string debugName = path;
log.Info("Mapping resource: {0}", debugName);
Stream rsrc = assembly.GetManifestResourceStream(path);
if (rsrc == null)
{
LogAndThrow(new MappingException("Resource not found: " + debugName));
}
try
{
return AddInputStream(rsrc, debugName);
}
catch (MappingException)
{
throw;
}
catch (Exception e)
{
LogAndThrow(new MappingException("Could not configure datastore from resource " + debugName, e));
return this; // To please the compiler
}
finally
{
if (rsrc != null)
{
rsrc.Close();
}
}
}
/// <summary>
/// Adds the mappings from embedded resources of the assembly.
/// </summary>
/// <param name="paths">Paths to the resource files in the assembly.</param>
/// <param name="assembly">The assembly that contains the resource files.</param>
/// <returns>This configuration object.</returns>
public Configuration AddResources(IEnumerable<string> paths, Assembly assembly)
{
if (paths == null)
{
throw new ArgumentNullException("paths");
}
foreach (var path in paths)
{
AddResource(path, assembly);
}
return this;
}
/// <summary>
/// Read a mapping from an embedded resource, using a convention.
/// </summary>
/// <param name="persistentClass">The type to map.</param>
/// <returns>This configuration object.</returns>
/// <remarks>
/// The convention is for class <c>Foo.Bar.Foo</c> to be mapped by
/// the resource named <c>Foo.Bar.Foo.hbm.xml</c>, embedded in
/// the class' assembly. If the mappings and classes are defined
/// in different assemblies or don't follow the naming convention,
/// this method cannot be used.
/// </remarks>
public Configuration AddClass(System.Type persistentClass)
{
return AddResource(persistentClass.FullName + ".hbm.xml", persistentClass.Assembly);
}
/// <summary>
/// Adds all of the assembly's embedded resources whose names end with <c>.hbm.xml</c>.
/// </summary>
/// <param name="assemblyName">The name of the assembly to load.</param>
/// <returns>This configuration object.</returns>
/// <remarks>
/// The assembly must be loadable using <see cref="Assembly.Load(string)" />. If this
/// condition is not satisfied, load the assembly manually and call
/// <see cref="AddAssembly(Assembly)"/> instead.
/// </remarks>
public Configuration AddAssembly(string assemblyName)
{
log.Info("Searching for mapped documents in assembly: {0}", assemblyName);
Assembly assembly = null;
try
{
assembly = Assembly.Load(assemblyName);
}
catch (Exception e)
{
LogAndThrow(new MappingException("Could not add assembly " + assemblyName, e));
}
return AddAssembly(assembly);
}
/// <summary>
/// Adds all of the assembly's embedded resources whose names end with <c>.hbm.xml</c>.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>This configuration object.</returns>
public Configuration AddAssembly(Assembly assembly)
{
IList<string> resourceNames = GetAllHbmXmlResourceNames(assembly);
if (resourceNames.Count == 0)
{
log.Warn("No mapped documents found in assembly: {0}", assembly.FullName);
}
foreach (var name in resourceNames)
{
AddResource(name, assembly);
}
return this;
}
private static List<string> GetAllHbmXmlResourceNames(Assembly assembly)
{
var result = new List<string>();
foreach (var resource in assembly.GetManifestResourceNames())
{
if (resource.EndsWith(".hbm.xml"))
{
result.Add(resource);
}
}
return result;
}
/// <summary>
/// Read all mapping documents from a directory tree. Assume that any
/// file named <c>*.hbm.xml</c> is a mapping document.
/// </summary>
/// <param name="dir">a directory</param>
public Configuration AddDirectory(DirectoryInfo dir)
{
foreach (var subDirectory in dir.GetDirectories())
{
AddDirectory(subDirectory);
}
foreach (var hbmXml in dir.GetFiles("*.hbm.xml"))
{
AddFile(hbmXml);
}
return this;
}
/// <summary>
/// Generate DDL for dropping tables
/// </summary>
/// <seealso cref="NHibernate.Tool.hbm2ddl.SchemaExport" />
public string[] GenerateDropSchemaScript(Dialect.Dialect dialect)
{
SecondPassCompile();
var defaultCatalog = GetQuotedDefaultCatalog(dialect);
var defaultSchema = GetQuotedDefaultSchema(dialect);
var script = new List<string>();
if (!dialect.SupportsForeignKeyConstraintInAlterTable && !string.IsNullOrEmpty(dialect.DisableForeignKeyConstraintsString))
script.Add(dialect.DisableForeignKeyConstraintsString);
// drop them in reverse order in case db needs it done that way...););
for (int i = auxiliaryDatabaseObjects.Count - 1; i >= 0; i--)
{
IAuxiliaryDatabaseObject auxDbObj = auxiliaryDatabaseObjects[i];
if (auxDbObj.AppliesToDialect(dialect))
{
script.Add(auxDbObj.SqlDropString(dialect, defaultCatalog, defaultSchema));
}
}
if (dialect.DropConstraints)
{
foreach (var table in TableMappings)
{
if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Drop))
{
foreach (var fk in table.ForeignKeyIterator)
{
if (fk.IsGenerated(dialect) && IncludeAction(fk.ReferencedTable.SchemaActions, SchemaAction.Drop))
{
script.Add(fk.SqlDropString(dialect, defaultCatalog, defaultSchema));
}
}
}
}
}
foreach (var table in TableMappings)
{
if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Drop))
{
script.Add(table.SqlDropString(dialect, defaultCatalog, defaultSchema));
}
}
IEnumerable<IPersistentIdentifierGenerator> pIDg = IterateGenerators(dialect);
foreach (var idGen in pIDg)
{
string[] lines = idGen.SqlDropString(dialect);
if (lines != null)
{
foreach (var line in lines)
{
script.Add(line);
}
}
}
if (!dialect.SupportsForeignKeyConstraintInAlterTable && !string.IsNullOrEmpty(dialect.EnableForeignKeyConstraintsString))
script.Add(dialect.EnableForeignKeyConstraintsString);
return script.ToArray();
}
public static bool IncludeAction(SchemaAction actionsSource, SchemaAction includedAction)
{
return (actionsSource & includedAction) != SchemaAction.None;
}
/// <summary>
/// Generate DDL for creating tables
/// </summary>
/// <param name="dialect"></param>
public string[] GenerateSchemaCreationScript(Dialect.Dialect dialect)
{
SecondPassCompile();
var defaultCatalog = GetQuotedDefaultCatalog(dialect);
var defaultSchema = GetQuotedDefaultSchema(dialect);
var script = new List<string>();
var staticDialectMapping = new StaticDialectMappingWrapper(mapping, dialect);
foreach (var table in TableMappings)
{
if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Export))
{
script.Add(table.SqlCreateString(dialect, staticDialectMapping, defaultCatalog, defaultSchema));
script.AddRange(table.SqlCommentStrings(dialect, defaultCatalog, defaultSchema));
}
}
foreach (var table in TableMappings)
{
if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Export))
{
if (!dialect.SupportsUniqueConstraintInCreateAlterTable)
{
foreach (var uk in table.UniqueKeyIterator)
{
string constraintString = uk.SqlCreateString(dialect, staticDialectMapping, defaultCatalog, defaultSchema);
if (constraintString != null)
{
script.Add(constraintString);
}
}
}
foreach (var index in table.IndexIterator)
{
script.Add(index.SqlCreateString(dialect, staticDialectMapping, defaultCatalog, defaultSchema));
}
if (dialect.SupportsForeignKeyConstraintInAlterTable)
{
foreach (var fk in table.ForeignKeyIterator)
{
if (fk.IsGenerated(dialect) && IncludeAction(fk.ReferencedTable.SchemaActions, SchemaAction.Export))
{
script.Add(fk.SqlCreateString(dialect, staticDialectMapping, defaultCatalog, defaultSchema));
}
}
}
}
}
IEnumerable<IPersistentIdentifierGenerator> pIDg = IterateGenerators(dialect);
foreach (var idGen in pIDg)
{
script.AddRange(idGen.SqlCreateStrings(dialect));
}
foreach (var auxDbObj in auxiliaryDatabaseObjects)
{
if (auxDbObj.AppliesToDialect(dialect))