PageRenderTime 92ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Backup/SubSonic.Core/Query/Insert.cs

https://bitbucket.org/moisesmiranda/subsonic-4
C# | 293 lines | 177 code | 35 blank | 81 comment | 10 complexity | 564620d8cfb746cf9cfcc0bf97166a1c MD5 | raw file
  1. //
  2. // SubSonic - http://subsonicproject.com
  3. //
  4. // The contents of this file are subject to the New BSD
  5. // License (the "License"); you may not use this file
  6. // except in compliance with the License. You may obtain a copy of
  7. // the License at http://www.opensource.org/licenses/bsd-license.php
  8. //
  9. // Software distributed under the License is distributed on an
  10. // "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  11. // implied. See the License for the specific language governing
  12. // rights and limitations under the License.
  13. //
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Data;
  17. using System.Linq.Expressions;
  18. using System.Text;
  19. using SubSonic.Extensions;
  20. using SubSonic.DataProviders;
  21. using SubSonic.Query;
  22. using SubSonic.Schema;
  23. using SubSonic.SqlGeneration;
  24. namespace SubSonic.Query
  25. {
  26. public class InsertSetting
  27. {
  28. internal string ColumnName = String.Empty;
  29. internal DbType DataType = DbType.AnsiString;
  30. internal bool IsExpression;
  31. internal string ParameterName = String.Empty;
  32. internal object Value;
  33. }
  34. /// <summary>
  35. ///
  36. /// </summary>
  37. public class Insert : ISqlQuery
  38. {
  39. private readonly IDataProvider _provider;
  40. public List<string> ColumnList = new List<string>();
  41. public List<InsertSetting> Inserts = new List<InsertSetting>();
  42. internal SqlQuery SelectValues;
  43. internal ITable Table;
  44. private string tableName = "";
  45. /// <summary>
  46. /// Initializes a new instance of the <see cref="Insert"/> class.
  47. /// </summary>
  48. public Insert() : this(ProviderFactory.GetProvider()) {}
  49. /// <summary>
  50. /// Initializes a new instance of the <see cref="Insert"/> class.
  51. /// </summary>
  52. /// <param name="provider">The provider.</param>
  53. public Insert(IDataProvider provider)
  54. {
  55. _provider = provider;
  56. }
  57. internal string SelectColumns
  58. {
  59. get { return ColumnList.ToDelimitedList(); }
  60. }
  61. #region ISqlQuery Members
  62. /// <summary>
  63. /// Builds the SQL statement.
  64. /// </summary>
  65. /// <returns></returns>
  66. public string BuildSqlStatement()
  67. {
  68. SqlQuery q = new SqlQuery(_provider);
  69. ISqlGenerator generator = q.GetGenerator();
  70. generator.SetInsertQuery(this);
  71. string sql = generator.BuildInsertStatement();
  72. return sql;
  73. }
  74. #endregion
  75. public Insert Into<T>(params Expression<Func<T, object>>[] props)
  76. {
  77. ColumnList.Clear();
  78. Table = _provider.FindOrCreateTable(typeof(T));
  79. tableName = Table.Name;
  80. Init();
  81. foreach(object o in props)
  82. {
  83. LambdaExpression lamba = o as LambdaExpression;
  84. ColumnList.Add(lamba.ParseObjectValue());
  85. }
  86. return this;
  87. }
  88. /// <summary>
  89. /// Adds the specified columns into a new Insert object.
  90. /// </summary>
  91. /// <typeparam name="T"></typeparam>
  92. /// <param name="columns">The columns.</param>
  93. /// <returns></returns>
  94. public Insert Into<T>(params string[] columns) where T : new()
  95. {
  96. ColumnList.Clear();
  97. ColumnList.AddRange(columns);
  98. Table = _provider.FindOrCreateTable(typeof(T));
  99. tableName = Table.Name;
  100. Init();
  101. return this; //Init(new T().GetSchema());
  102. }
  103. /// <summary>
  104. /// Adds the specified columns into a new Insert object.
  105. /// </summary>
  106. /// <typeparam name="T"></typeparam>
  107. /// <param name="tbl">The TBL.</param>
  108. /// <returns></returns>
  109. public Insert Into<T>(ITable tbl) where T : new()
  110. {
  111. ColumnList.Clear();
  112. Table = tbl;
  113. tableName = tbl.Name;
  114. Init();
  115. return this;
  116. }
  117. /// <summary>
  118. /// Inits this instance.
  119. /// </summary>
  120. /// <returns></returns>
  121. private Insert Init()
  122. {
  123. if(Table==null)
  124. throw new InvalidOperationException("No table is set");
  125. // EK: No methods consume the return value. Is the rest of this necessary?
  126. bool isFirst = true;
  127. StringBuilder sb = new StringBuilder();
  128. foreach(string s in ColumnList)
  129. {
  130. if(!isFirst)
  131. sb.Append(",");
  132. sb.Append(s);
  133. isFirst = false;
  134. }
  135. return this;
  136. }
  137. private Insert AddValues(bool isExpression, params object[] values)
  138. {
  139. //this is a lineup game
  140. //make sure that the count of values
  141. //is equal to the columns
  142. if(values.Length != ColumnList.Count)
  143. throw new InvalidOperationException("The Select list and value list don't match - they need to match exactly if you're creating an INSERT VALUES query");
  144. int itemIndex = 0;
  145. foreach(string s in ColumnList)
  146. {
  147. AddInsertSetting(s, values[itemIndex], DbType.AnsiString, isExpression);
  148. itemIndex++;
  149. }
  150. return this;
  151. }
  152. private void AddInsertSetting(string columnName, object columnValue, DbType dbType, bool isExpression)
  153. {
  154. InsertSetting setting = new InsertSetting
  155. {
  156. ColumnName = columnName,
  157. ParameterName = _provider.ParameterPrefix + "ins_" + columnName.ToAlphaNumericOnly(),
  158. Value = columnValue,
  159. IsExpression = isExpression,
  160. DataType = dbType
  161. };
  162. Inserts.Add(setting);
  163. }
  164. /// <summary>
  165. /// Values the specified column.
  166. /// </summary>
  167. /// <param name="column">The column.</param>
  168. /// <param name="columnValue">The column value.</param>
  169. /// <returns></returns>
  170. public Insert Value(string column, object columnValue)
  171. {
  172. AddInsertSetting(column, columnValue, DbType.AnsiString, false);
  173. ColumnList.Add(column);
  174. return this;
  175. }
  176. /// <summary>
  177. /// Values the specified column.
  178. /// </summary>
  179. /// <param name="column">The column.</param>
  180. /// <param name="columnValue">The column value.</param>
  181. /// <param name="dbType">Type of the db.</param>
  182. /// <returns></returns>
  183. public Insert Value(string column, object columnValue, DbType dbType)
  184. {
  185. AddInsertSetting(column, columnValue, dbType, false);
  186. ColumnList.Add(column);
  187. return this;
  188. }
  189. /// <summary>
  190. /// Valueses the specified values.
  191. /// </summary>
  192. /// <param name="values">The values.</param>
  193. /// <returns></returns>
  194. public Insert Values(params object[] values)
  195. {
  196. return AddValues(false, values);
  197. }
  198. /// <summary>
  199. /// Values the expression.
  200. /// </summary>
  201. /// <param name="values">The values.</param>
  202. /// <returns></returns>
  203. public Insert ValueExpression(params object[] values)
  204. {
  205. return AddValues(true, values);
  206. }
  207. /// <summary>
  208. /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
  209. /// </summary>
  210. /// <returns>
  211. /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
  212. /// </returns>
  213. public override string ToString()
  214. {
  215. return BuildSqlStatement();
  216. }
  217. #region Execution
  218. public IDataReader ExecuteReader()
  219. {
  220. return _provider.ExecuteReader(GetCommand());
  221. }
  222. /// <summary>
  223. /// Executes this instance.
  224. /// </summary>
  225. /// <returns></returns>
  226. public int Execute()
  227. {
  228. int returner = 0;
  229. object result = _provider.ExecuteScalar(GetCommand());
  230. if(result != null)
  231. {
  232. if(result.GetType() == typeof(decimal))
  233. returner = Convert.ToInt32(result);
  234. if(result.GetType() == typeof(int))
  235. returner = Convert.ToInt32(result);
  236. }
  237. return returner;
  238. }
  239. public QueryCommand GetCommand()
  240. {
  241. string sql = BuildSqlStatement();
  242. QueryCommand cmd = new QueryCommand(sql, _provider);
  243. //add in the commands
  244. foreach(InsertSetting s in Inserts)
  245. {
  246. QueryParameter p = new QueryParameter
  247. {
  248. ParameterName = s.ParameterName,
  249. ParameterValue = s.Value ?? DBNull.Value,
  250. DataType = s.DataType
  251. };
  252. cmd.Parameters.Add(p);
  253. }
  254. return cmd;
  255. }
  256. #endregion
  257. }
  258. }