2 // XmlSchemaDataImporter.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
10 // ***** The design note became somewhat obsolete. Should be rewritten. *****
16 // This class is used to import an XML Schema into a DataSet schema.
18 // Only XmlReader is acceptable as the input to the class.
19 // This class is not expected to read XML Schema multi time.
21 // ** Targetable Schema Components
23 // Only global global elements that hold complex type are converted
26 // The components of the type of the element are subsequently converted
27 // into a table, BUT there is an exception. As for "DataSet elements",
28 // the type is just ignored (see "DataSet Element definition" below).
30 // The components of the type of the element are subsequently converted
31 // into a table. As for "DataSet elements", its complex type is also
35 // Unused complex types are never be converted.
37 // Global simple types and global attributes are never converted.
38 // They cannot be a table.
39 // Local complex types are also converted into a table.
41 // Local elements are converted into either a table or a column in
42 // the "context DataTable". Simple-typed element is not always converted
43 // into a DataColumn; if maxOccurs > 1, it will be converted as a table.
47 // Ignore this section. Microsoft.NET was buggy enough to confuse
48 // against these name conflicts.
50 // Since local complex types are anonymous, we have to name for each
51 // component. Thus, and since complex types and elements can have the
52 // same name each other, we have to manage a table for mappings from
53 // a name to a component. The names must be also used in DataRelation
54 // definitions correctly.
56 // ** DataSet element definition
58 // "DataSet element" is 1) such element that has an attribute
59 // msdata:IsDataSet (where prefix "msdata" is bound to
60 // urn:schemas-microsoft-com:xml-msdata), or 2) the only one
61 // element definition in the schema.
63 // There is another complicated rule. 1) If there is only one element EL
64 // in the schema, and 2) if the type of EL is complex named CT, and 3)
65 // the content of the CT is a group base, and 4) the group base contains
66 // an element EL2, and finally 5) if EL2 is complex, THEN the element is
67 // the DataSet element.
69 // Only the first global element that matches the condition above is
70 // regarded as DataSet element (by necessary design or just a bug?)
71 // instead of handling as an error.
73 // All global elements are considered as an alternative in the dataset
76 // For local elements, msdata:IsDataSet are just ignored.
78 // ** Importing Complex Types as Columns
80 // When an xs:element is going to be mapped, its complex type (remember
81 // that only complex-typed elements are targettable) are expanded to
84 // DataColumn has a property MappingType that shows whether this column
85 // came from attribute or element.
87 // [Question: How about MappingType.Simple? How is it used?]
89 // Additionally, for particle elements, it might also create another
90 // DataTable (but for the particle elements in context DataTable, it
91 // will create an index to the new table).
93 // For group base particles (XmlSchemaGroupBase; sequence, choice, all)
94 // each component in those groups are mapped to a column. Even if you
95 // import "choice" or "all" components, DataSet.WriteXmlSchema() will
96 // output them just as a "sequence".
98 // Columns cannot be added directly to current context DataTable; they
99 // need to be added after processing all the columns, because they may
100 // have msdata:Ordinal attribute that specifies the order of the columns
103 // "Nested elements" are not allowed. (Clarification required?)
105 // ** Identity Constraints and DataRelations
107 // *** DataRelations from element identity constraints
109 // Only constraints on "DataSet element" is considered. All other
110 // constraint definitions are ignored. Note that it is DataSet that has
111 // the property Relations (of type DataRelationCollection).
113 // xs:key and xs:unique are handled as the same (then both will be
114 // serialized as xs:unique).
116 // The XPath expressions in the constraints are strictly limited; they
117 // are expected to be expandable enough to be mappable for each
119 // * selector to "any_valid_XPath/is/OK/blah"
120 // where "blah" is one of the DataTable name. It looks that
121 // only the last QName section is significant and any heading
122 // XPath step is OK (even if the mapped node does not exist).
123 // * field to QName that is mapped to DataColumn in the DataTable
124 // (even ./QName is not allowed)
126 // *** DataRelations from annotations
128 // See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/_mapping_relationship_specified_for_nested_elements.asp and http://msdn.microsoft.com/library/en-us/cpguide/html/_specifying_relationship_between_elements_with_no_nesting.asp
130 // ** Informative References
132 // Generating DataSet Relational Structure from XML Schema (XSD)
133 // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/_generating_dataset_relational_structure_from_xsd.asp
137 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
139 // Permission is hereby granted, free of charge, to any person obtaining
140 // a copy of this software and associated documentation files (the
141 // "Software"), to deal in the Software without restriction, including
142 // without limitation the rights to use, copy, modify, merge, publish,
143 // distribute, sublicense, and/or sell copies of the Software, and to
144 // permit persons to whom the Software is furnished to do so, subject to
145 // the following conditions:
147 // The above copyright notice and this permission notice shall be
148 // included in all copies or substantial portions of the Software.
150 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
151 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
152 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
153 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
154 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
155 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
156 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
160 using System.Collections;
162 using System.Globalization;
164 using System.Xml.Schema;
167 namespace System.Data
169 internal class TableStructureCollection : CollectionBase
171 public void Add (TableStructure table)
176 public TableStructure this [int i] {
177 get { return List [i] as TableStructure; }
180 public TableStructure this [string name] {
182 foreach (TableStructure ts in List)
183 if (ts.Table.TableName == name)
190 internal class RelationStructureCollection : CollectionBase
192 public void Add (RelationStructure rel)
197 public RelationStructure this [int i] {
198 get { return List [i] as RelationStructure; }
201 public RelationStructure this [string parent, string child] {
203 foreach (RelationStructure rel in List)
204 if (rel.ParentTableName == parent && rel.ChildTableName == child)
211 internal class TableStructure
213 public TableStructure (DataTable table)
218 // The columns and orders which will be added to the context
219 // table (See design notes; Because of the ordinal problem)
220 public DataTable Table;
221 public Hashtable OrdinalColumns = new Hashtable ();
222 public ArrayList NonOrdinalColumns = new ArrayList ();
223 public DataColumn PrimaryKey;
225 public bool ContainsColumn (string name)
227 foreach (DataColumn col in NonOrdinalColumns)
228 if (col.ColumnName == name)
230 foreach (DataColumn col in OrdinalColumns.Keys)
231 if (col.ColumnName == name)
237 internal class RelationStructure
239 public string ExplicitName;
240 public string ParentTableName;
241 public string ChildTableName;
242 public string ParentColumnName;
243 public string ChildColumnName;
244 public bool IsNested;
245 public bool CreateConstraint;
248 internal class ConstraintStructure
250 public readonly string TableName;
251 public readonly string [] Columns;
252 public readonly bool [] IsAttribute;
253 public readonly string ConstraintName;
254 public readonly bool IsPrimaryKey;
255 public readonly string ReferName;
256 public readonly bool IsNested;
257 public readonly bool IsConstraintOnly;
259 public ConstraintStructure (string tname, string [] cols, bool [] isAttr, string cname, bool isPK, string refName, bool isNested, bool isConstraintOnly)
263 IsAttribute = isAttr;
264 ConstraintName = XmlHelper.Decode (cname);
268 IsConstraintOnly = isConstraintOnly;
272 internal class XmlSchemaDataImporter
274 static readonly XmlSchemaDatatype schemaIntegerType;
275 static readonly XmlSchemaDatatype schemaDecimalType;
276 static readonly XmlSchemaComplexType schemaAnyType;
278 static XmlSchemaDataImporter ()
280 XmlSchema s = new XmlSchema ();
281 XmlSchemaAttribute a = new XmlSchemaAttribute ();
283 a.SchemaTypeName = new XmlQualifiedName ("integer", XmlSchema.Namespace);
285 XmlSchemaAttribute b = new XmlSchemaAttribute ();
287 b.SchemaTypeName = new XmlQualifiedName ("decimal", XmlSchema.Namespace);
289 XmlSchemaElement e = new XmlSchemaElement ();
293 schemaIntegerType = a.AttributeType as XmlSchemaDatatype;
294 schemaDecimalType = b.AttributeType as XmlSchemaDatatype;
295 schemaAnyType = e.ElementType as XmlSchemaComplexType;
303 ArrayList relations = new ArrayList ();
304 Hashtable reservedConstraints = new Hashtable ();
306 // such element that has an attribute msdata:IsDataSet="true"
307 XmlSchemaElement datasetElement;
309 // choice alternatives in the "dataset element"
310 ArrayList topLevelElements = new ArrayList ();
312 // import target elements
313 ArrayList targetElements = new ArrayList ();
315 TableStructure currentTable;
321 public XmlSchemaDataImporter (DataSet dataset, XmlReader reader)
323 this.dataset = dataset;
324 dataset.DataSetName = "NewDataSet"; // Initialize always
325 schema = XmlSchema.Read (reader, null);
326 if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "schema" && reader.NamespaceURI == XmlSchema.Namespace)
327 reader.ReadEndElement ();
328 schema.Compile (null);
333 public void Process ()
335 if (schema.Id != null)
336 dataset.DataSetName = schema.Id; // default. Overridable by "DataSet element"
337 dataset.Namespace = schema.TargetNamespace;
339 // Find dataset element
340 foreach (XmlSchemaObject obj in schema.Items) {
341 XmlSchemaElement el = obj as XmlSchemaElement;
343 if (datasetElement == null &&
344 IsDataSetElement (el))
346 if (el.ElementType is XmlSchemaComplexType &&
347 el.ElementType != schemaAnyType)
348 targetElements.Add (obj);
352 // make reservation of identity constraints
353 if (datasetElement != null) {
355 foreach (XmlSchemaObject obj in datasetElement.Constraints)
356 if (! (obj is XmlSchemaKeyref))
357 ReserveSelfIdentity ((XmlSchemaIdentityConstraint) obj);
359 foreach (XmlSchemaObject obj in datasetElement.Constraints)
360 if (obj is XmlSchemaKeyref)
361 ReserveRelationIdentity (datasetElement, (XmlSchemaKeyref) obj);
364 foreach (XmlSchemaObject obj in schema.Items) {
365 if (obj is XmlSchemaElement) {
366 XmlSchemaElement el = obj as XmlSchemaElement;
367 if (el.ElementType is XmlSchemaComplexType &&
368 el.ElementType != schemaAnyType)
369 targetElements.Add (obj);
373 // This collection will grow up while processing elements.
374 int globalElementCount = targetElements.Count;
376 for (int i = 0; i < globalElementCount; i++)
377 ProcessGlobalElement ((XmlSchemaElement) targetElements [i]);
379 // Rest are local elements.
380 for (int i = globalElementCount; i < targetElements.Count; i++)
381 ProcessDataTableElement ((XmlSchemaElement) targetElements [i]);
383 // Handle relation definitions written as xs:annotation.
384 // See detail: http://msdn.microsoft.com/library/shared/happyUrl/fnf_msdn.asp?Redirect=%22http://msdn.microsoft.com/404/default.asp%22
385 foreach (XmlSchemaObject obj in schema.Items)
386 if (obj is XmlSchemaAnnotation)
387 HandleAnnotations ((XmlSchemaAnnotation) obj, false);
389 if (datasetElement != null) {
390 // Handle constraints in the DataSet element. First keys.
391 foreach (XmlSchemaObject obj in datasetElement.Constraints)
392 if (! (obj is XmlSchemaKeyref))
393 ProcessSelfIdentity (reservedConstraints [obj] as ConstraintStructure);
395 foreach (XmlSchemaObject obj in datasetElement.Constraints)
396 if (obj is XmlSchemaKeyref)
397 ProcessRelationIdentity (datasetElement, reservedConstraints [obj] as ConstraintStructure);
400 foreach (RelationStructure rs in this.relations)
401 dataset.Relations.Add (GenerateRelationship (rs));
404 private bool IsDataSetElement (XmlSchemaElement el)
406 if (el.UnhandledAttributes != null) {
407 foreach (XmlAttribute attr in el.UnhandledAttributes) {
408 if (attr.LocalName == "IsDataSet" &&
409 attr.NamespaceURI == XmlConstants.MsdataNamespace) {
410 switch (attr.Value) {
411 case "true": // case sensitive
416 throw new DataException (String.Format ("Value {0} is invalid for attribute 'IsDataSet'.", attr.Value));
422 if (schema.Elements.Count != 1)
424 if (!(el.SchemaType is XmlSchemaComplexType))
426 XmlSchemaComplexType ct = (XmlSchemaComplexType) el.SchemaType;
427 if (ct.AttributeUses.Count > 0)
429 XmlSchemaGroupBase gb = ct.ContentTypeParticle as XmlSchemaGroupBase;
430 if (gb == null || gb.Items.Count == 0)
432 foreach (XmlSchemaParticle p in gb.Items) {
433 if (ContainsColumn (p))
439 private bool ContainsColumn (XmlSchemaParticle p)
441 XmlSchemaElement el = p as XmlSchemaElement;
443 XmlSchemaComplexType ct = el.ElementType as XmlSchemaComplexType;
444 if (ct == null || ct == schemaAnyType)
445 return true; // column element
446 if (ct.AttributeUses.Count > 0)
447 return false; // table element
448 if (ct.ContentType == XmlSchemaContentType.TextOnly)
449 return true; // column element
451 return false; // table element
453 XmlSchemaGroupBase gb = p as XmlSchemaGroupBase;
454 for (int i = 0; i < gb.Items.Count; i++) {
455 if (ContainsColumn ((XmlSchemaParticle) gb.Items [i]))
461 private void ProcessGlobalElement (XmlSchemaElement el)
463 // If it is already registered (by resolving reference
464 // in previously-imported elements), just ignore.
465 if (dataset.Tables.Contains (el.QualifiedName.Name))
468 // If type is not complex, just skip this element
469 if (! (el.ElementType is XmlSchemaComplexType && el.ElementType != schemaAnyType))
472 if (IsDataSetElement (el)) {
473 ProcessDataSetElement (el);
477 // Register as a top-level element
478 topLevelElements.Add (el);
479 // Create DataTable for this element
480 ProcessDataTableElement (el);
483 private void ProcessDataSetElement (XmlSchemaElement el)
485 dataset.DataSetName = el.Name;
486 this.datasetElement = el;
488 // Search for msdata:Locale attribute
489 if (el.UnhandledAttributes != null) {
490 foreach (XmlAttribute attr in el.UnhandledAttributes) {
491 if (attr.LocalName == "Locale" &&
492 attr.NamespaceURI == XmlConstants.MsdataNamespace) {
493 CultureInfo ci = new CultureInfo (attr.Value);
499 // Process content type particle (and create DataTable)
500 XmlSchemaComplexType ct = el.ElementType as XmlSchemaComplexType;
501 XmlSchemaParticle p = ct != null ? ct.ContentTypeParticle : null;
503 HandleDataSetContentTypeParticle (p);
506 private void HandleDataSetContentTypeParticle (XmlSchemaParticle p)
508 XmlSchemaElement el = p as XmlSchemaElement;
510 if (el.ElementType is XmlSchemaComplexType && el.RefName != el.QualifiedName)
511 ProcessDataTableElement (el);
513 else if (p is XmlSchemaGroupBase) {
514 foreach (XmlSchemaParticle pc in ((XmlSchemaGroupBase) p).Items)
515 HandleDataSetContentTypeParticle (pc);
519 private void ProcessDataTableElement (XmlSchemaElement el)
521 string tableName = XmlHelper.Decode (el.QualifiedName.Name);
522 // If it is already registered, just ignore.
523 if (dataset.Tables.Contains (tableName))
526 DataTable table = new DataTable (tableName);
527 table.Namespace = el.QualifiedName.Namespace;
528 currentTable = new TableStructure (table);
530 dataset.Tables.Add (table);
533 if (el.UnhandledAttributes != null) {
534 foreach (XmlAttribute attr in el.UnhandledAttributes) {
535 if (attr.LocalName == "Locale" &&
536 attr.NamespaceURI == XmlConstants.MsdataNamespace)
537 table.Locale = new CultureInfo (attr.Value);
541 // Handle complex type (NOTE: It is (or should be)
542 // impossible the type is other than complex type).
543 XmlSchemaComplexType ct = (XmlSchemaComplexType) el.ElementType;
546 foreach (DictionaryEntry de in ct.AttributeUses)
547 ImportColumnAttribute ((XmlSchemaAttribute) de.Value);
549 // Handle content type particle
550 if (ct.ContentTypeParticle is XmlSchemaElement)
551 ImportColumnElement (el, (XmlSchemaElement) ct.ContentTypeParticle);
552 else if (ct.ContentTypeParticle is XmlSchemaGroupBase)
553 ImportColumnGroupBase (el, (XmlSchemaGroupBase) ct.ContentTypeParticle);
554 // else if null then do nothing.
556 // Handle simple content
557 switch (ct.ContentType) {
558 case XmlSchemaContentType.TextOnly:
559 // case XmlSchemaContentType.Mixed:
560 // LAMESPEC: When reading from XML Schema, it maps to "_text", while on the data inference, it is mapped to "_Text" (case ignorant).
561 string simpleName = el.QualifiedName.Name + "_text";
562 DataColumn simple = new DataColumn (simpleName);
563 simple.Namespace = el.QualifiedName.Namespace;
564 simple.AllowDBNull = (el.MinOccurs == 0);
565 simple.ColumnMapping = MappingType.SimpleContent;
566 simple.DataType = ConvertDatatype (ct.Datatype);
567 currentTable.NonOrdinalColumns.Add (simple);
571 // add columns to the table in specified order
572 // (by msdata:Ordinal attributes)
573 SortedList sd = new SortedList ();
574 foreach (DictionaryEntry de in currentTable.OrdinalColumns)
575 sd.Add (de.Value, de.Key);
576 foreach (DictionaryEntry de in sd)
577 table.Columns.Add ((DataColumn) de.Value);
578 foreach (DataColumn dc in currentTable.NonOrdinalColumns)
579 table.Columns.Add (dc);
582 private DataRelation GenerateRelationship (RelationStructure rs)
584 DataTable ptab = dataset.Tables [rs.ParentTableName];
585 DataTable ctab = dataset.Tables [rs.ChildTableName];
588 string name = rs.ExplicitName != null ? rs.ExplicitName : XmlHelper.Decode (ptab.TableName) + '_' + XmlHelper.Decode (ctab.TableName);
590 // Annotation Relations belonging to a DataSet can contain multiple colnames
591 // in parentkey and childkey.
592 if (datasetElement != null) {
593 String[] pcolnames = rs.ParentColumnName.Split (null);
594 String[] ccolnames = rs.ChildColumnName.Split (null);
596 DataColumn[] pcol = new DataColumn [pcolnames.Length];
597 for (int i=0; i<pcol.Length; ++i)
598 pcol [i] = ptab.Columns [XmlHelper.Decode (pcolnames [i])];
600 DataColumn[] ccol = new DataColumn [ccolnames.Length];
601 for (int i=0; i < ccol.Length; ++i) {
602 ccol [i] = ctab.Columns [XmlHelper.Decode (ccolnames [i])];
603 if (ccol [i] == null)
604 ccol [i] = CreateChildColumn (pcol [i], ctab);
606 rel = new DataRelation (name, pcol, ccol, rs.CreateConstraint);
608 DataColumn pcol = ptab.Columns [XmlHelper.Decode (rs.ParentColumnName)];
609 DataColumn ccol = ctab.Columns [XmlHelper.Decode (rs.ChildColumnName)];
611 ccol = CreateChildColumn (pcol, ctab);
612 rel = new DataRelation (name, pcol, ccol, rs.CreateConstraint);
614 rel.Nested = rs.IsNested;
615 if (rs.CreateConstraint)
616 rel.ParentTable.PrimaryKey = rel.ParentColumns;
620 private DataColumn CreateChildColumn (DataColumn parentColumn, DataTable childTable)
622 DataColumn col = childTable.Columns.Add (parentColumn.ColumnName,
623 parentColumn.DataType);
624 col.Namespace = String.Empty;
625 col.ColumnMapping = MappingType.Hidden;
629 private void ImportColumnGroupBase (XmlSchemaElement parent, XmlSchemaGroupBase gb)
631 foreach (XmlSchemaParticle p in gb.Items) {
632 XmlSchemaElement el = p as XmlSchemaElement;
634 ImportColumnElement (parent, el);
635 else if (p is XmlSchemaGroupBase)
636 ImportColumnGroupBase (parent, (XmlSchemaGroupBase) p);
637 // otherwise p is xs:any
641 private XmlSchemaDatatype GetSchemaPrimitiveType (object type)
643 if (type is XmlSchemaComplexType)
644 return null; // It came here, so that maybe it is xs:anyType
645 XmlSchemaDatatype dt = type as XmlSchemaDatatype;
646 if (dt == null && type != null)
647 dt = ((XmlSchemaSimpleType) type).Datatype;
651 // Note that this column might be Hidden
652 private void ImportColumnAttribute (XmlSchemaAttribute attr)
654 DataColumn col = new DataColumn ();
655 col.ColumnName = attr.QualifiedName.Name;
656 col.Namespace = attr.QualifiedName.Namespace;
657 XmlSchemaDatatype dt = GetSchemaPrimitiveType (attr.AttributeType);
658 // This complicated check comes from the fact that
659 // MS.NET fails to map System.Object to anyType (that
660 // will cause ReadTypedObject() fail on XmlValidatingReader).
661 // ONLY In DataSet context, we set System.String for
663 col.DataType = ConvertDatatype (dt);
664 if (col.DataType == typeof (object))
665 col.DataType = typeof (string);
666 // When attribute use="prohibited", then it is regarded as
668 if (attr.Use == XmlSchemaUse.Prohibited)
669 col.ColumnMapping = MappingType.Hidden;
671 col.ColumnMapping = MappingType.Attribute;
672 col.DefaultValue = GetAttributeDefaultValue (attr);
674 if (attr.Use == XmlSchemaUse.Required)
675 col.AllowDBNull = false;
677 FillFacet (col, attr.AttributeType as XmlSchemaSimpleType);
679 // Call this method after filling the name
680 ImportColumnMetaInfo (attr, attr.QualifiedName, col);
684 private void ImportColumnElement (XmlSchemaElement parent, XmlSchemaElement el)
686 // FIXME: element nest check
688 DataColumn col = new DataColumn ();
689 col.DefaultValue = GetElementDefaultValue (el);
690 col.AllowDBNull = (el.MinOccurs == 0);
692 if (el.ElementType is XmlSchemaComplexType && el.ElementType != schemaAnyType)
693 FillDataColumnComplexElement (parent, el, col);
694 else if (el.MaxOccurs != 1)
695 FillDataColumnRepeatedSimpleElement (parent, el, col);
697 FillDataColumnSimpleElement (el, col);
700 // common process for element and attribute
701 private void ImportColumnMetaInfo (XmlSchemaAnnotated obj, XmlQualifiedName name, DataColumn col)
704 if (obj.UnhandledAttributes != null) {
705 foreach (XmlAttribute attr in obj.UnhandledAttributes) {
706 if (attr.NamespaceURI != XmlConstants.MsdataNamespace)
708 switch (attr.LocalName) {
709 case XmlConstants.Caption:
710 col.Caption = attr.Value;
712 case XmlConstants.DataType:
713 col.DataType = Type.GetType (attr.Value);
715 case XmlConstants.AutoIncrement:
716 col.AutoIncrement = bool.Parse (attr.Value);
718 case XmlConstants.AutoIncrementSeed:
719 col.AutoIncrementSeed = int.Parse (attr.Value);
721 case XmlConstants.AutoIncrementStep:
722 col.AutoIncrementStep = int.Parse (attr.Value);
724 case XmlConstants.ReadOnly:
725 col.ReadOnly = XmlConvert.ToBoolean (attr.Value);
727 case XmlConstants.Ordinal:
728 ordinal = int.Parse (attr.Value);
735 private void FillDataColumnComplexElement (XmlSchemaElement parent, XmlSchemaElement el, DataColumn col)
737 if (targetElements.Contains (el))
738 return; // do nothing
740 string elName = XmlHelper.Decode (el.QualifiedName.Name);
741 if (elName == dataset.DataSetName)
742 // Well, why it is ArgumentException :-?
743 throw new ArgumentException ("Nested element must not have the same name as DataSet's name.");
745 if (el.Annotation != null)
746 HandleAnnotations (el.Annotation, true);
747 // If xsd:keyref xsd:key for this table exists, then don't add
748 // relation here manually.
749 else if (!DataSetDefinesKey (elName)) {
750 AddParentKeyColumn (parent, el, col);
752 RelationStructure rel = new RelationStructure ();
753 rel.ParentTableName = XmlHelper.Decode (parent.QualifiedName.Name);
754 rel.ChildTableName = elName;
755 rel.ParentColumnName = col.ColumnName;
756 rel.ChildColumnName = col.ColumnName;
757 rel.CreateConstraint = true;
762 // If the element is not referenced one, the element will be handled later.
763 if (el.RefName == XmlQualifiedName.Empty)
764 targetElements.Add (el);
768 private bool DataSetDefinesKey (string name)
770 foreach (ConstraintStructure c in reservedConstraints.Values)
771 if (c.TableName == name && (c.IsPrimaryKey || c.IsNested))
776 private void AddParentKeyColumn (XmlSchemaElement parent, XmlSchemaElement el, DataColumn col)
778 if (currentTable.PrimaryKey != null)
781 // check name identity
782 string name = XmlHelper.Decode (parent.QualifiedName.Name) + "_Id";
784 while (currentTable.ContainsColumn (name))
785 name = String.Format ("{0}_{1}", name, count++);
786 // check existing primary key
787 if (currentTable.Table.PrimaryKey.Length > 0)
788 throw new DataException (String.Format ("There is already primary key columns in the table \"{0}\".", currentTable.Table.TableName));
790 col.ColumnName = name;
791 col.ColumnMapping = MappingType.Hidden;
792 col.Namespace = parent.QualifiedName.Namespace;
793 col.DataType = typeof (int);
794 col.AutoIncrement = true;
795 col.AllowDBNull = false;
797 ImportColumnMetaInfo (el, el.QualifiedName, col);
799 currentTable.PrimaryKey = col;
802 private void FillDataColumnRepeatedSimpleElement (XmlSchemaElement parent, XmlSchemaElement el, DataColumn col)
804 if (targetElements.Contains (el))
805 return; // do nothing
807 AddParentKeyColumn (parent, el, col);
808 DataColumn pkey = currentTable.PrimaryKey;
810 string elName = XmlHelper.Decode (el.QualifiedName.Name);
811 string parentName = XmlHelper.Decode (parent.QualifiedName.Name);
813 DataTable dt = new DataTable ();
814 dt.TableName = elName;
815 dt.Namespace = el.QualifiedName.Namespace;
816 // reference key column to parent
817 DataColumn cc = new DataColumn ();
818 cc.ColumnName = parentName + "_Id";
819 cc.Namespace = parent.QualifiedName.Namespace;
820 cc.ColumnMapping = MappingType.Hidden;
821 cc.DataType = typeof (int);
823 // repeatable content simple element
824 DataColumn cc2 = new DataColumn ();
825 cc2.ColumnName = elName + "_Column";
826 cc2.Namespace = el.QualifiedName.Namespace;
827 cc2.ColumnMapping = MappingType.SimpleContent;
828 cc2.AllowDBNull = false;
829 cc2.DataType = ConvertDatatype (GetSchemaPrimitiveType (el.ElementType));
831 dt.Columns.Add (cc2);
833 dataset.Tables.Add (dt);
835 RelationStructure rel = new RelationStructure ();
836 rel.ParentTableName = parentName;
837 rel.ChildTableName = dt.TableName;
838 rel.ParentColumnName = pkey.ColumnName;
839 rel.ChildColumnName = cc.ColumnName;
841 rel.CreateConstraint = true;
845 private void FillDataColumnSimpleElement (XmlSchemaElement el, DataColumn col)
847 col.ColumnName = XmlHelper.Decode (el.QualifiedName.Name);
848 col.Namespace = el.QualifiedName.Namespace;
849 col.ColumnMapping = MappingType.Element;
850 col.DataType = ConvertDatatype (GetSchemaPrimitiveType (el.ElementType));
851 FillFacet (col, el.ElementType as XmlSchemaSimpleType);
853 ImportColumnMetaInfo (el, el.QualifiedName, col);
858 private void AddColumn (DataColumn col)
861 currentTable.NonOrdinalColumns.Add (col);
863 currentTable.OrdinalColumns.Add (col, col.Ordinal);
866 private void FillFacet (DataColumn col, XmlSchemaSimpleType st)
868 if (st == null || st.Content == null)
871 // Handle restriction facets
873 XmlSchemaSimpleTypeRestriction restriction = st == null ? null : st.Content as XmlSchemaSimpleTypeRestriction;
874 if (restriction == null)
875 throw new DataException ("DataSet does not suport 'list' nor 'union' simple type.");
877 foreach (XmlSchemaFacet f in restriction.Facets) {
878 if (f is XmlSchemaMaxLengthFacet)
879 // There is no reason why MaxLength is limited to int, except for the fact that DataColumn.MaxLength property is int.
880 col.MaxLength = int.Parse (f.Value);
884 private Type ConvertDatatype (XmlSchemaDatatype dt)
887 return typeof (string);
888 else if (dt.ValueType == typeof (decimal)) {
889 // LAMESPEC: MSDN documentation says it is based
890 // on ValueType. However, in the System.Xml.Schema
891 // context, xs:integer is mapped to Decimal, while
892 // in DataSet context it is mapped to Int64.
893 if (dt == schemaDecimalType)
894 return typeof (decimal);
895 else if (dt == schemaIntegerType)
896 return typeof (long);
898 return typeof (ulong);
904 // This method cuts out the local name of the last step from XPath.
905 // It is nothing more than hack. However, MS looks to do similar.
906 private string GetSelectorTarget (string xpath)
908 string tableName = xpath;
909 int index = tableName.LastIndexOf ('/');
910 // '>' is enough. If XPath [0] = '/', it is invalid.
911 // Selector can specify only element axes.
913 tableName = tableName.Substring (index + 1);
915 // Round QName to NSName
916 index = tableName.LastIndexOf (':');
918 tableName = tableName.Substring (index + 1);
920 return XmlHelper.Decode (tableName);
923 private void ReserveSelfIdentity (XmlSchemaIdentityConstraint ic)
925 string tableName = GetSelectorTarget (ic.Selector.XPath);
927 string [] cols = new string [ic.Fields.Count];
928 bool [] isAttrSpec = new bool [cols.Length];
931 foreach (XmlSchemaXPath Field in ic.Fields) {
932 string colName = Field.XPath;
933 bool isAttr = colName.Length > 0 && colName [0] == '@';
934 int index = colName.LastIndexOf (':');
936 colName = colName.Substring (index + 1);
938 colName = colName.Substring (1);
940 colName = XmlHelper.Decode (colName);
942 isAttrSpec [i] = isAttr;
947 // find if there is an attribute with the constraint name
948 // if not use the XmlSchemaConstraint's name.
949 string constraintName = ic.Name;
950 if (ic.UnhandledAttributes != null) {
951 foreach (XmlAttribute attr in ic.UnhandledAttributes) {
952 if (attr.NamespaceURI != XmlConstants.MsdataNamespace)
954 switch (attr.LocalName) {
955 case XmlConstants.ConstraintName:
956 constraintName = attr.Value;
958 case XmlConstants.PrimaryKey:
959 isPK = bool.Parse(attr.Value);
964 reservedConstraints.Add (ic,
965 new ConstraintStructure (tableName, cols,
966 isAttrSpec, constraintName, isPK, null, false, false));
969 private void ProcessSelfIdentity (ConstraintStructure c)
971 // Basic concept came from XmlSchemaMapper.cs
973 string tableName = c.TableName;
975 DataTable dt = dataset.Tables [tableName];
977 throw new DataException (String.Format ("Invalid XPath selection inside selector. Cannot find: {0}", tableName));
979 DataColumn [] cols = new DataColumn [c.Columns.Length];
980 for (int i = 0; i < cols.Length; i++) {
981 string colName = c.Columns [i];
982 bool isAttr = c.IsAttribute [i];
983 DataColumn col = dt.Columns [colName];
985 throw new DataException (String.Format ("Invalid XPath selection inside field. Cannot find: {0}", tableName));
986 if (isAttr && col.ColumnMapping != MappingType.Attribute)
987 throw new DataException ("The XPath specified attribute field, but mapping type is not attribute.");
988 if (!isAttr && col.ColumnMapping != MappingType.Element)
989 throw new DataException ("The XPath specified simple element field, but mapping type is not simple element.");
991 cols [i] = dt.Columns [colName];
994 bool isPK = c.IsPrimaryKey;
995 string constraintName = c.ConstraintName;
996 dt.Constraints.Add (new UniqueConstraint (
997 constraintName, cols, isPK));
1000 private void ReserveRelationIdentity (XmlSchemaElement element, XmlSchemaKeyref keyref)
1002 // Basic concept came from XmlSchemaMapper.cs
1004 string tableName = GetSelectorTarget (keyref.Selector.XPath);
1006 string [] cols = new string [keyref.Fields.Count];
1007 bool [] isAttrSpec = new bool [cols.Length];
1009 foreach (XmlSchemaXPath Field in keyref.Fields) {
1010 string colName = Field.XPath;
1011 bool isAttr = colName.Length > 0 && colName [0] == '@';
1012 int index = colName.LastIndexOf (':');
1014 colName = colName.Substring (index + 1);
1016 colName = colName.Substring (1);
1018 colName = XmlHelper.Decode (colName);
1020 isAttrSpec [i] = isAttr;
1023 string constraintName = keyref.Name;
1024 bool isNested = false;
1025 bool isConstraintOnly = false;
1026 if (keyref.UnhandledAttributes != null) {
1027 foreach (XmlAttribute attr in keyref.UnhandledAttributes) {
1028 if (attr.NamespaceURI != XmlConstants.MsdataNamespace)
1030 switch (attr.LocalName) {
1031 case XmlConstants.ConstraintName:
1032 constraintName = attr.Value;
1034 case XmlConstants.IsNested:
1035 if (attr.Value == "true")
1038 case XmlConstants.ConstraintOnly:
1039 if (attr.Value == "true")
1040 isConstraintOnly = true;
1046 reservedConstraints.Add (keyref, new ConstraintStructure (
1047 tableName, cols, isAttrSpec, constraintName,
1048 false, keyref.Refer.Name, isNested, isConstraintOnly));
1051 private void ProcessRelationIdentity (XmlSchemaElement element, ConstraintStructure c)
1053 // Basic concept came from XmlSchemaMapper.cs
1055 string tableName = c.TableName;
1058 DataTable dt = dataset.Tables [tableName];
1060 throw new DataException (String.Format ("Invalid XPath selection inside selector. Cannot find: {0}", tableName));
1062 cols = new DataColumn [c.Columns.Length];
1063 for (int i = 0; i < cols.Length; i++) {
1064 string colName = c.Columns [i];
1065 bool isAttr = c.IsAttribute [i];
1066 DataColumn col = dt.Columns [colName];
1067 if (isAttr && col.ColumnMapping != MappingType.Attribute)
1068 throw new DataException ("The XPath specified attribute field, but mapping type is not attribute.");
1069 if (!isAttr && col.ColumnMapping != MappingType.Element)
1070 throw new DataException ("The XPath specified simple element field, but mapping type is not simple element.");
1073 string name = c.ReferName;
1074 // get the unique constraint for the releation
1075 UniqueConstraint uniq = FindConstraint (name, element);
1077 ForeignKeyConstraint fkc = new ForeignKeyConstraint(c.ConstraintName, uniq.Columns, cols);
1078 dt.Constraints.Add (fkc);
1080 if (!c.IsConstraintOnly) {
1081 // generate the relation.
1082 DataRelation rel = new DataRelation (c.ConstraintName, uniq.Columns, cols, false);
1083 rel.Nested = c.IsNested;
1084 rel.SetParentKeyConstraint (uniq);
1085 rel.SetChildKeyConstraint (fkc);
1087 dataset.Relations.Add (rel);
1091 // get the unique constraint for the relation.
1092 // name - the name of the XmlSchemaUnique element
1093 private UniqueConstraint FindConstraint (string name, XmlSchemaElement element)
1095 // Copied from XmlSchemaMapper.cs
1097 // find the element in the constraint collection.
1098 foreach (XmlSchemaIdentityConstraint c in element.Constraints) {
1099 if (c is XmlSchemaKeyref)
1102 if (c.Name == name) {
1103 string tableName = GetSelectorTarget (c.Selector.XPath);
1105 // find the table in the dataset.
1106 DataTable dt = dataset.Tables [tableName];
1108 string constraintName = c.Name;
1109 // find if there is an attribute with the constraint name
1110 // if not use the XmlSchemaUnique name.
1111 if (c.UnhandledAttributes != null)
1112 foreach (XmlAttribute attr in c.UnhandledAttributes)
1113 if (attr.LocalName == "ConstraintName" && attr.NamespaceURI == XmlConstants.MsdataNamespace)
1114 constraintName = attr.Value;
1115 return (UniqueConstraint) dt.Constraints [constraintName];
1118 throw new DataException ("Target identity constraint was not found: " + name);
1121 private void HandleAnnotations (XmlSchemaAnnotation an, bool nested)
1123 foreach (XmlSchemaObject content in an.Items) {
1124 XmlSchemaAppInfo ai = content as XmlSchemaAppInfo;
1126 foreach (XmlNode n in ai.Markup) {
1127 XmlElement el = n as XmlElement;
1128 if (el != null && el.LocalName == "Relationship" && el.NamespaceURI == XmlConstants.MsdataNamespace)
1129 HandleRelationshipAnnotation (el, nested);
1135 private void HandleRelationshipAnnotation (XmlElement el, bool nested)
1137 string name = el.GetAttribute ("name");
1138 string ptn = el.GetAttribute ("parent", XmlConstants.MsdataNamespace);
1139 string ctn = el.GetAttribute ("child", XmlConstants.MsdataNamespace);
1140 string pkn = el.GetAttribute ("parentkey", XmlConstants.MsdataNamespace);
1141 string fkn = el.GetAttribute ("childkey", XmlConstants.MsdataNamespace);
1143 RelationStructure rel = new RelationStructure ();
1144 rel.ExplicitName = XmlHelper.Decode (name);
1145 rel.ParentTableName = XmlHelper.Decode (ptn);
1146 rel.ChildTableName = XmlHelper.Decode (ctn);
1147 // ColumnNames will be decoded wherever they are used as they can
1148 // contain 'space' separated list of column-names.
1149 rel.ParentColumnName = pkn;
1150 rel.ChildColumnName = fkn;
1151 rel.IsNested = nested;
1152 rel.CreateConstraint = false; // by default?
1153 relations.Add (rel);
1156 private object GetElementDefaultValue (XmlSchemaElement elem)
1158 // Unlike attribute, element cannot have a default value.
1159 if (elem.RefName == XmlQualifiedName.Empty)
1160 return elem.DefaultValue;
1161 XmlSchemaElement referenced = schema.Elements [elem.RefName] as XmlSchemaElement;
1162 if (referenced == null) // considering missing sub components
1164 return referenced.DefaultValue;
1167 private object GetAttributeDefaultValue (XmlSchemaAttribute attr)
1169 #if BUGGY_MS_COMPATIBLE
1172 else if (attr.RefName != XmlQualifiedName.Empty) {
1173 XmlSchemaAttribute referenced = schema.Attributes [attr.RefName] as XmlSchemaAttribute;
1174 if (referenced != null)
1175 return referenced.DefaultValue;
1179 if (attr.DefaultValue != null)
1180 return attr.DefaultValue;
1181 return attr.FixedValue;
1183 if (attr.DefaultValue != null)
1184 return attr.DefaultValue;
1185 else if (attr.FixedValue != null)
1186 return attr.FixedValue;
1187 else if (attr.RefName == XmlQualifiedName.Empty)
1189 XmlSchemaAttribute referenced = schema.Attributes [attr.RefName] as XmlSchemaAttribute;
1190 if (referenced == null) // considering missing sub components
1192 if (referenced.DefaultValue != null)
1193 return referenced.DefaultValue;
1194 return referenced.FixedValue;