PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/Source/nHydrate.Generator.SQLInstaller/ProjectItemGenerators/SQLStoredProcedureAll/SQLPagedSelectComponentTemplate.cs

#
C# | 341 lines | 269 code | 31 blank | 41 comment | 31 complexity | 99e6ec3a4b244072a77cf0a32193dff1 MD5 | raw file
Possible License(s): JSON, CC-BY-SA-3.0
  1. #region Copyright (c) 2006-2012 nHydrate.org, All Rights Reserved
  2. //--------------------------------------------------------------------- *
  3. // NHYDRATE.ORG *
  4. // Copyright (c) 2006-2012 All Rights reserved *
  5. // *
  6. // *
  7. //This file and its contents are protected by United States and *
  8. //International copyright laws. Unauthorized reproduction and/or *
  9. //distribution of all or any portion of the code contained herein *
  10. //is strictly prohibited and will result in severe civil and criminal *
  11. //penalties. Any violations of this copyright will be prosecuted *
  12. //to the fullest extent possible under law. *
  13. // *
  14. //THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED *
  15. //TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND *
  16. //TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
  17. //CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY *
  18. //THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF THE NHYDRATE GROUP *
  19. // *
  20. //UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN *
  21. //PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR *
  22. //SUBSTANTIALLY THE SAME, FUNCTIONALITY AS THIS PRODUCT *
  23. // *
  24. //THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE *
  25. //CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF NHYDRATE, *
  26. //THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO *
  27. //INSURE ITS CONFIDENTIALITY. *
  28. // *
  29. //THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT *
  30. //PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN *
  31. //EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING *
  32. //THE PRODUCT. IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE *
  33. //SOURCE CODE CONTAINED HEREIN. *
  34. // *
  35. //THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. *
  36. //--------------------------------------------------------------------- *
  37. #endregion
  38. using System;
  39. using System.Linq;
  40. using System.Collections;
  41. using System.Collections.Generic;
  42. using System.Text;
  43. using nHydrate.Generator.Models;
  44. using nHydrate.Generator.Common.Util;
  45. using nHydrate.Generator.Common.GeneratorFramework;
  46. namespace nHydrate.Generator.SQLInstaller.ProjectItemGenerators.SQLStoredProcedureAll
  47. {
  48. class SQLPagedSelectComponentTemplate : ISQLGenerate
  49. {
  50. private ModelRoot _model;
  51. private TableComponent _currentComponent;
  52. #region Constructors
  53. public SQLPagedSelectComponentTemplate(ModelRoot model, TableComponent currentComponent)
  54. {
  55. _model = model;
  56. _currentComponent = currentComponent;
  57. }
  58. #endregion
  59. #region GenerateContent
  60. public void GenerateContent(StringBuilder sb)
  61. {
  62. if (_model.Database.AllowZeroTouch) return;
  63. if (!_model.SupportLegacySearchObject) return;
  64. try
  65. {
  66. this.AppendFullTemplate(sb);
  67. }
  68. catch (Exception ex)
  69. {
  70. throw;
  71. }
  72. }
  73. #endregion
  74. private void AppendFullTemplate(StringBuilder sb)
  75. {
  76. try
  77. {
  78. sb.AppendLine("if exists (select * from dbo.sysobjects where id = object_id(N'[" + _currentComponent.GetSQLSchema() + "].[" + StoredProcedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
  79. sb.AppendLine(" drop procedure [" + _currentComponent.GetSQLSchema() + "].[" + StoredProcedureName + "]");
  80. sb.AppendLine("GO");
  81. sb.AppendLine();
  82. sb.AppendLine("SET QUOTED_IDENTIFIER ON ");
  83. sb.AppendLine("GO");
  84. sb.AppendLine("SET ANSI_NULLS ON");
  85. sb.AppendLine("GO");
  86. sb.AppendLine();
  87. sb.AppendLine("CREATE PROCEDURE [" + _currentComponent.GetSQLSchema() + "].[" + StoredProcedureName + "]");
  88. sb.AppendLine("(");
  89. sb.AppendLine(" @page [Int], -- page number selected by the user");
  90. sb.AppendLine(" @pageSize [Int], -- number of items on the page");
  91. sb.AppendLine(" @orderByColumn [Varchar] (100), -- name of column to order things by");
  92. sb.AppendLine(" @ascending [Bit], -- order column ascending or descending");
  93. sb.AppendLine(" @filter [Varchar] (100) = null, -- filter statement passed in to determine like criteria on order by column");
  94. sb.AppendLine(" @count [Int] out -- number of items in the collection");
  95. sb.AppendLine(")");
  96. sb.AppendLine("AS");
  97. sb.AppendLine();
  98. sb.AppendLine("SET NOCOUNT ON;");
  99. sb.AppendLine();
  100. this.BuildPagingSelect(sb);
  101. sb.AppendLine();
  102. sb.AppendLine("GO");
  103. sb.AppendLine();
  104. sb.AppendLine("SET QUOTED_IDENTIFIER OFF");
  105. sb.AppendLine("GO");
  106. sb.AppendLine("SET ANSI_NULLS ON");
  107. sb.AppendLine("GO");
  108. if (!string.IsNullOrEmpty(_model.Database.GrantExecUser))
  109. {
  110. sb.AppendFormat("GRANT EXECUTE ON [" + _currentComponent.GetSQLSchema() + "].[{0}] TO [{1}]", StoredProcedureName, _model.Database.GrantExecUser).AppendLine();
  111. sb.AppendLine("GO");
  112. sb.AppendLine();
  113. }
  114. }
  115. catch (Exception ex)
  116. {
  117. throw;
  118. }
  119. }
  120. #region string methods
  121. private void BuildPagingSelect(StringBuilder sb)
  122. {
  123. try
  124. {
  125. List<Column> allColumns = new List<Column>();
  126. foreach (Reference reference in _currentComponent.Columns)
  127. {
  128. Column column = (Column)reference.Object;
  129. if (!(column.DataType == System.Data.SqlDbType.Binary ||
  130. column.DataType == System.Data.SqlDbType.Image ||
  131. column.DataType == System.Data.SqlDbType.NText ||
  132. column.DataType == System.Data.SqlDbType.Text ||
  133. column.DataType == System.Data.SqlDbType.Timestamp ||
  134. column.DataType == System.Data.SqlDbType.Udt ||
  135. column.DataType == System.Data.SqlDbType.VarBinary ||
  136. column.DataType == System.Data.SqlDbType.Variant ||
  137. column.DataType == System.Data.SqlDbType.Money))
  138. {
  139. allColumns.Add(column);
  140. }
  141. }
  142. if (allColumns.Count != 0)
  143. {
  144. this.BuildStoredProcedure(sb, allColumns);
  145. }
  146. }
  147. catch (Exception ex)
  148. {
  149. throw new Exception(_currentComponent.DatabaseName + ": Failed on generation of paging select statement", ex);
  150. }
  151. }
  152. private void BuildStoredProcedure(StringBuilder sb, List<Column> allColumns)
  153. {
  154. int index = 0;
  155. sb.Append("CREATE TABLE #tmpTable");
  156. sb.AppendLine("(");
  157. foreach (Column column in _currentComponent.Parent.PrimaryKeyColumns.OrderBy(x => x.Name))
  158. {
  159. sb.Append("\t[" + column.DatabaseName + "] " + column.GetSQLDefaultType());
  160. if (index < _currentComponent.Parent.PrimaryKeyColumns.Count - 1) sb.Append(",");
  161. sb.AppendLine();
  162. index++;
  163. }
  164. //sb.Remove(sb.Length - 3, 3);
  165. sb.AppendLine(")");
  166. sb.AppendLine();
  167. sb.AppendLine("DECLARE @total__ivqatedr int");
  168. sb.AppendLine("DECLARE @orderByColumnIndex int");
  169. sb.AppendLine("-- remove top x values from the temp table based upon the specific page requested");
  170. sb.AppendLine("SET @total__ivqatedr = (@pageSize * @page)");
  171. sb.AppendLine("IF (@total__ivqatedr <> 0)");
  172. sb.AppendLine("BEGIN");
  173. sb.AppendLine(" SET ROWCOUNT @total__ivqatedr");
  174. sb.AppendLine("END");
  175. sb.AppendLine("INSERT INTO #tmpTable");
  176. sb.AppendLine("(");
  177. sb.Append(Globals.BuildPrimaryKeySelectList(_model, _currentComponent.Parent, false));
  178. sb.AppendLine(")");
  179. //SELECT CLAUSE
  180. sb.AppendLine("SELECT");
  181. sb.Append(Globals.BuildPrimaryKeySelectList(_model, _currentComponent.Parent, true));
  182. sb.AppendLine("FROM");
  183. sb.AppendLine(_currentComponent.Parent.GetFullHierarchyTableJoin());
  184. sb.AppendLine("WHERE");
  185. int ii = 0;
  186. foreach (Column column in allColumns.OrderBy(x => x.Name))
  187. {
  188. //If this is text then do a like, other wise equals
  189. string comparer = "=";
  190. if (ModelHelper.IsTextType(column.DataType))
  191. comparer = "LIKE";
  192. string tableName = Globals.GetTableDatabaseName(_model, (Table)column.ParentTableRef.Object);
  193. sb.Append(" (@orderByColumn = '" + column.DatabaseName + "' and (((@filter is null) or (" + tableName + ".[" + column.DatabaseName + "] is null)) or (@filter is not null and " + tableName + ".[" + column.DatabaseName + "] " + comparer + " @filter)))");
  194. if (ii < allColumns.Count - 1)
  195. {
  196. sb.AppendLine();
  197. sb.Append("or");
  198. }
  199. sb.AppendLine();
  200. ii++;
  201. }
  202. //ORDER BY CLAUSE
  203. sb.AppendLine("ORDER BY");
  204. ii = 0;
  205. foreach (var column in allColumns.Where(x => x.DataType != System.Data.SqlDbType.Xml &&
  206. x.DataType != System.Data.SqlDbType.Text &&
  207. x.DataType != System.Data.SqlDbType.NText &&
  208. x.DataType != System.Data.SqlDbType.Image).OrderBy(x => x.Name))
  209. {
  210. string tableName = Globals.GetTableDatabaseName(_model, (Table)column.ParentTableRef.Object);
  211. sb.AppendLine(" CASE @ascending WHEN 0 THEN CASE @orderByColumn WHEN '" + column.DatabaseName + "' THEN [" + tableName + "].[" + column.DatabaseName + "] END END DESC, ");
  212. sb.Append(" CASE @ascending WHEN 1 THEN CASE @orderByColumn WHEN '" + column.DatabaseName + "' THEN [" + tableName + "].[" + column.DatabaseName + "] END END");
  213. if (ii < allColumns.Count - 1)
  214. {
  215. sb.Append(", ");
  216. }
  217. sb.AppendLine();
  218. ii++;
  219. }
  220. sb.AppendLine();
  221. sb.AppendLine("-- set @count based on the rows moved in the previous statement");
  222. //sb.AppendLine("SET @count = ( SELECT count(*) FROM [#tmpTable] )");
  223. //REPEAT SELECT CLAUSE FOR COUNT
  224. sb.AppendLine("SET ROWCOUNT 0");
  225. sb.AppendLine("SET @count = (");
  226. sb.AppendLine("SELECT count(*)");
  227. sb.AppendLine("FROM");
  228. sb.AppendLine(_currentComponent.Parent.GetFullHierarchyTableJoin());
  229. sb.AppendLine("WHERE");
  230. ii = 0;
  231. foreach (Column column in allColumns.OrderBy(x => x.Name))
  232. {
  233. var t = column.ParentTableRef.Object as Table;
  234. string tableName = "[" + t.GetSQLSchema() + "].[" + Globals.GetTableDatabaseName(_model, t) + "]";
  235. string comparer = "=";
  236. if (ModelHelper.IsTextType(column.DataType))
  237. comparer = "LIKE";
  238. sb.Append(" (@orderByColumn = '" + column.DatabaseName + "' and (((@filter is null) or (" + tableName + ".[" + column.DatabaseName + "] is null)) or (@filter is not null and " + tableName + ".[" + column.DatabaseName + "] " + comparer + " @filter)))");
  239. if (ii < allColumns.Count - 1)
  240. {
  241. sb.AppendLine();
  242. sb.Append("or");
  243. }
  244. sb.AppendLine();
  245. ii++;
  246. }
  247. sb.AppendLine(")");
  248. sb.AppendLine();
  249. sb.AppendLine("-- remove top x values from the temp table based upon the specific page requested");
  250. sb.AppendLine("SET @total__ivqatedr = (@pageSize * @page) - @pageSize");
  251. sb.AppendLine("IF (@total__ivqatedr <> 0)");
  252. sb.AppendLine("BEGIN");
  253. sb.AppendLine(" SET ROWCOUNT @total__ivqatedr");
  254. sb.AppendLine(" DELETE FROM #tmpTable");
  255. sb.AppendLine("END");
  256. sb.AppendLine();
  257. sb.AppendLine("-- return the number of rows requested as the page size");
  258. sb.AppendLine("SET ROWCOUNT @pageSize");
  259. sb.AppendLine("SELECT");
  260. sb.Append(Globals.BuildSelectList(_currentComponent, _model));
  261. sb.AppendLine("FROM");
  262. sb.AppendLine("\t[#tmpTable]");
  263. sb.Append(" INNER JOIN " + _currentComponent.Parent.GetFullHierarchyTableJoin() + " ON ");
  264. bool pkFirstTime = true;
  265. foreach (Column pkColumn in _currentComponent.Parent.PrimaryKeyColumns.OrderBy(x => x.Name))
  266. {
  267. if (!pkFirstTime)
  268. {
  269. sb.AppendLine(" AND");
  270. }
  271. else
  272. {
  273. pkFirstTime = false;
  274. }
  275. sb.AppendFormat("#tmpTable.[{0}] = [{1}].[{0}]", pkColumn.DatabaseName.ToLower(), _currentComponent.Parent.PascalName.ToUpper());
  276. }
  277. sb.AppendLine();
  278. sb.AppendLine("ORDER BY");
  279. ii = 0;
  280. foreach (var column in allColumns.Where(x => x.DataType != System.Data.SqlDbType.Xml &&
  281. x.DataType != System.Data.SqlDbType.Text &&
  282. x.DataType != System.Data.SqlDbType.NText &&
  283. x.DataType != System.Data.SqlDbType.Image).OrderBy(x => x.Name))
  284. {
  285. string tableName = Globals.GetTableDatabaseName(_model, (Table)column.ParentTableRef.Object);
  286. sb.AppendLine(" CASE @ascending WHEN 0 THEN CASE @orderByColumn WHEN '" + column.DatabaseName + "' THEN [" + tableName + "].[" + column.DatabaseName + "] END END DESC, ");
  287. sb.Append(" CASE @ascending WHEN 1 THEN CASE @orderByColumn WHEN '" + column.DatabaseName + "' THEN [" + tableName + "].[" + column.DatabaseName + "] END END");
  288. if (ii < allColumns.Count - 1)
  289. {
  290. sb.Append(", ");
  291. }
  292. sb.AppendLine();
  293. ii++;
  294. }
  295. sb.AppendLine();
  296. sb.AppendLine("DROP TABLE #tmpTable");
  297. sb.AppendLine();
  298. sb.AppendLine("GO");
  299. sb.AppendLine("SET QUOTED_IDENTIFIER OFF");
  300. sb.AppendLine("GO");
  301. sb.AppendLine("SET ANSI_NULLS ON");
  302. sb.AppendLine("GO");
  303. }
  304. public string StoredProcedureName
  305. {
  306. get { return _model.GetStoredProcedurePrefix() + "_" + _currentComponent.PascalName + "PagingSelect"; }
  307. }
  308. #endregion
  309. }
  310. }