PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/development/Vulcan/Vulcan/Patterns/ETLPattern.cs

#
C# | 251 lines | 188 code | 32 blank | 31 comment | 16 complexity | 29f5c8aab4022b47e0744d0ab524f720 MD5 | raw file
  1. /*
  2. * Microsoft Public License (Ms-PL)
  3. *
  4. * This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
  5. *
  6. * 1. Definitions
  7. * The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
  8. * A "contribution" is the original software, or any additions or changes to the software.
  9. * A "contributor" is any person that distributes its contribution under this license.
  10. * "Licensed patents" are a contributor's patent claims that read directly on its contribution.
  11. *
  12. * 2. Grant of Rights
  13. * (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
  14. * (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
  15. *
  16. * 3. Conditions and Limitations
  17. * (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
  18. * (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
  19. * (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
  20. * (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
  21. * (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
  22. */
  23. using System;
  24. using System.Collections.Generic;
  25. using System.Text;
  26. using System.Text.RegularExpressions;
  27. using System.IO;
  28. using System.Xml;
  29. using System.Xml.XPath;
  30. using Vulcan.Common;
  31. using Vulcan.Tasks;
  32. using Vulcan.Common.Templates;
  33. using Vulcan.Transformations;
  34. using Vulcan.Emitters;
  35. using Vulcan.Properties;
  36. using DTS = Microsoft.SqlServer.Dts.Runtime;
  37. using Microsoft.SqlServer.Dts.Runtime.Wrapper;
  38. using Microsoft.SqlServer.Dts.Pipeline;
  39. using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
  40. namespace Vulcan.Patterns
  41. {
  42. public class ETLPattern : Pattern
  43. {
  44. private List<Vulcan.Tasks.PrecedenceConstraint> pcList = new List<Vulcan.Tasks.PrecedenceConstraint>();
  45. public ETLPattern(Packages.VulcanPackage vulcanPackage, DTS.IDTSSequence parentContainer)
  46. :
  47. base(
  48. vulcanPackage,
  49. parentContainer
  50. )
  51. {
  52. }
  53. public override void Emit(XPathNavigator patternNavigator)
  54. {
  55. // Reloads invalidate the ParentContainer, so we should do it much later.
  56. string etlName =
  57. patternNavigator.SelectSingleNode("@Name", VulcanPackage.VulcanConfig.NamespaceManager).Value;
  58. Message.Trace(Severity.Notification, "{0}", etlName);
  59. bool delayValidation = patternNavigator.SelectSingleNode("@DelayValidation").ValueAsBoolean;
  60. string sourceName = patternNavigator.SelectSingleNode("rc:SourceConnection/@Name", VulcanPackage.VulcanConfig.NamespaceManager).Value;
  61. Connection sourceConnection =
  62. Connection.GetExistingConnection(
  63. VulcanPackage,
  64. patternNavigator.SelectSingleNode("rc:SourceConnection/@Name", VulcanPackage.VulcanConfig.NamespaceManager).Value
  65. );
  66. if (sourceConnection != null)
  67. {
  68. string query = patternNavigator.SelectSingleNode("rc:Query", VulcanPackage.VulcanConfig.NamespaceManager).Value.Trim();
  69. // Add the Data Flow Task to the Package.
  70. DTS.TaskHost pipeHost = (DTS.TaskHost)ParentContainer.Executables.Add("STOCK:PipelineTask");
  71. pipeHost.Properties["DelayValidation"].SetValue(pipeHost, delayValidation);
  72. MainPipe dataFlowTask = (MainPipe)pipeHost.InnerObject;
  73. pipeHost.Name = etlName;
  74. // Add the Source (this is temporary and will be replaced with a new style of Source element)
  75. IDTSComponentMetaData90 sourceDataComponent = dataFlowTask.ComponentMetaDataCollection.New();
  76. sourceDataComponent.ComponentClassID = "DTSAdapter.OleDbSource.1";
  77. // IMPORTANT! If you do not Instantiate() and ProvideComponentProperties first,
  78. // the component names do not get set... this is bad.
  79. CManagedComponentWrapper oleInstance = sourceDataComponent.Instantiate();
  80. oleInstance.ProvideComponentProperties();
  81. sourceDataComponent.Name = etlName + " Source";
  82. if (sourceDataComponent.RuntimeConnectionCollection.Count > 0)
  83. {
  84. sourceDataComponent.RuntimeConnectionCollection[0].ConnectionManager =
  85. DTS.DtsConvert.ToConnectionManager90(
  86. sourceConnection.ConnectionManager
  87. );
  88. sourceDataComponent.RuntimeConnectionCollection[0].ConnectionManagerID =
  89. sourceConnection.ConnectionManager.ID;
  90. }
  91. oleInstance.SetComponentProperty("AccessMode", 2);
  92. oleInstance.SetComponentProperty("SqlCommand", query);
  93. try
  94. {
  95. oleInstance.AcquireConnections(null);
  96. oleInstance.ReinitializeMetaData();
  97. oleInstance.ReleaseConnections();
  98. }
  99. catch (System.Runtime.InteropServices.COMException ce)
  100. {
  101. Message.Trace(Severity.Error, ce, "OLEDBSource:{0}: {1}: Source {2}: Query {3}", sourceDataComponent.GetErrorDescription(ce.ErrorCode), ce.Message, sourceConnection.ConnectionManager.Name, query);
  102. }
  103. catch (Exception e)
  104. {
  105. Message.Trace(Severity.Error, e, "OLEDBSource:{0}: Source {1}: Query {2}", e.Message, sourceConnection.ConnectionManager.Name, query);
  106. }
  107. //Map parameter variables:
  108. StringBuilder parameterBuilder = new StringBuilder();
  109. foreach (XPathNavigator paramNav in patternNavigator.Select("rc:Parameter", VulcanPackage.VulcanConfig.NamespaceManager))
  110. {
  111. string name = paramNav.SelectSingleNode("@Name").Value;
  112. string varName = paramNav.SelectSingleNode("@VariableName").Value;
  113. if (VulcanPackage.DTSPackage.Variables.Contains(varName))
  114. {
  115. DTS.Variable variable = VulcanPackage.DTSPackage.Variables[varName];
  116. parameterBuilder.AppendFormat("\"{0}\",{1};", name, variable.ID);
  117. }
  118. else
  119. {
  120. Message.Trace(Severity.Error, "DTS Variable {0} does not exist", varName);
  121. }
  122. }
  123. oleInstance.SetComponentProperty("ParameterMapping", parameterBuilder.ToString());
  124. ///Transformation Factory
  125. IDTSComponentMetaData90 parentComponent = sourceDataComponent;
  126. XPathNavigator transNav = patternNavigator.SelectSingleNode("rc:Transformations", VulcanPackage.VulcanConfig.NamespaceManager);
  127. if (transNav != null)
  128. {
  129. foreach (XPathNavigator nav in transNav.SelectChildren(XPathNodeType.Element))
  130. {
  131. // this is naughty but can be fixed later :)
  132. Transformation t = TransformationFactory.ProcessTransformation(VulcanPackage, parentComponent, dataFlowTask, nav);
  133. if (t != null)
  134. {
  135. parentComponent = t.Component;
  136. }
  137. }
  138. }
  139. XPathNavigator destNav = patternNavigator.SelectSingleNode("rc:Destination", VulcanPackage.VulcanConfig.NamespaceManager);
  140. if (destNav != null)
  141. {
  142. string name = destNav.SelectSingleNode("@Name").Value;
  143. Connection destConnection = Connection.GetExistingConnection(VulcanPackage, destNav.SelectSingleNode("@ConnectionName").Value);
  144. string tableName = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}", destNav.SelectSingleNode("@Table").Value.Trim());
  145. OLEDBDestination oledbDestination = new OLEDBDestination(VulcanPackage, dataFlowTask, parentComponent, name, name, destConnection, tableName);
  146. string accessMode = destNav.SelectSingleNode("@AccessMode").Value;
  147. bool tableLock = destNav.SelectSingleNode("@TableLock").ValueAsBoolean;
  148. bool checkConstraints = destNav.SelectSingleNode("@CheckConstraints").ValueAsBoolean;
  149. bool keepIdentity = destNav.SelectSingleNode("@KeepIdentity").ValueAsBoolean;
  150. bool keepNulls = destNav.SelectSingleNode("@KeepNulls").ValueAsBoolean;
  151. int rowsPerBatch = destNav.SelectSingleNode("@RowsPerBatch").ValueAsInt;
  152. int maxInsertCommitSize = destNav.SelectSingleNode("@MaximumInsertCommitSize").ValueAsInt;
  153. switch (accessMode.ToUpperInvariant())
  154. {
  155. case "TABLE":
  156. oledbDestination.ComponentInstance.SetComponentProperty("AccessMode", 0);
  157. oledbDestination.ComponentInstance.SetComponentProperty("OpenRowset", tableName);
  158. break;
  159. case "TABLEFASTLOAD":
  160. oledbDestination.ComponentInstance.SetComponentProperty("AccessMode", 3);
  161. oledbDestination.ComponentInstance.SetComponentProperty("OpenRowset", tableName);
  162. oledbDestination.ComponentInstance.SetComponentProperty("FastLoadKeepIdentity", keepIdentity);
  163. oledbDestination.ComponentInstance.SetComponentProperty("FastLoadKeepNulls", keepNulls);
  164. oledbDestination.ComponentInstance.SetComponentProperty("FastLoadMaxInsertCommitSize", maxInsertCommitSize);
  165. StringBuilder fastLoadOptions = new StringBuilder();
  166. if (tableLock)
  167. {
  168. fastLoadOptions.AppendFormat("TABLOCK,");
  169. }
  170. if (checkConstraints)
  171. {
  172. fastLoadOptions.AppendFormat("CHECK_CONSTRAINTS,");
  173. }
  174. if (rowsPerBatch > 0)
  175. {
  176. fastLoadOptions.AppendFormat("ROWS_PER_BATCH = {0}", rowsPerBatch);
  177. }
  178. fastLoadOptions = fastLoadOptions.Replace(",", "",fastLoadOptions.Length-5,5);
  179. oledbDestination.ComponentInstance.SetComponentProperty("FastLoadOptions", fastLoadOptions.ToString());
  180. break;
  181. default:
  182. Message.Trace(Severity.Error, "Unknown Destination Load Type of {0}", accessMode);
  183. break;
  184. }
  185. try
  186. {
  187. oledbDestination.InitializeAndMapDestination();
  188. }
  189. catch (Exception)
  190. {
  191. }
  192. // Map any overrides
  193. foreach (XPathNavigator nav in destNav.Select("rc:Map", VulcanPackage.VulcanConfig.NamespaceManager))
  194. {
  195. string source = nav.SelectSingleNode("@Source").Value;
  196. string destination;
  197. bool unMap = false;
  198. if (nav.SelectSingleNode("@Destination") == null)
  199. {
  200. unMap = true;
  201. destination = source;
  202. }
  203. else
  204. {
  205. destination = nav.SelectSingleNode("@Destination").Value;
  206. }
  207. oledbDestination.Map(source, destination, unMap);
  208. }
  209. } // end DestNav != null
  210. this.FirstExecutableGeneratedByPattern = pipeHost;
  211. this.LastExecutableGeneratedByPattern = pipeHost;
  212. } //END sourceConnection != null
  213. else
  214. {
  215. Message.Trace(Severity.Error, "Source Connection {0} does not exist in {1}", sourceName, etlName);
  216. }
  217. } //END function Emit
  218. } //END CLASS ETLPattern
  219. }//END namespace