SqlCommandSet.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. //------------------------------------------------------------------------------
  2. // <copyright file="SqlBatchCommand.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data.SqlClient {
  9. using System;
  10. using System.Collections.Generic;
  11. using System.ComponentModel;
  12. using System.Data;
  13. using System.Data.Common;
  14. using System.Diagnostics;
  15. using System.Globalization;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. internal sealed class SqlCommandSet {
  19. private const string SqlIdentifierPattern = "^@[\\p{Lo}\\p{Lu}\\p{Ll}\\p{Lm}_@#][\\p{Lo}\\p{Lu}\\p{Ll}\\p{Lm}\\p{Nd}\uff3f_@#\\$]*$";
  20. private static readonly Regex SqlIdentifierParser = new Regex(SqlIdentifierPattern, RegexOptions.ExplicitCapture|RegexOptions.Singleline);
  21. private List<LocalCommand> _commandList = new List<LocalCommand>();
  22. private SqlCommand _batchCommand;
  23. private static int _objectTypeCount; // Bid counter
  24. internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
  25. private sealed class LocalCommand {
  26. internal readonly string CommandText;
  27. internal readonly SqlParameterCollection Parameters;
  28. internal readonly int ReturnParameterIndex;
  29. internal readonly CommandType CmdType;
  30. internal LocalCommand(string commandText, SqlParameterCollection parameters, int returnParameterIndex, CommandType cmdType) {
  31. Debug.Assert(0 <= commandText.Length, "no text");
  32. this.CommandText = commandText;
  33. this.Parameters = parameters;
  34. this.ReturnParameterIndex = returnParameterIndex;
  35. this.CmdType = cmdType;
  36. }
  37. }
  38. internal SqlCommandSet() : base() {
  39. _batchCommand = new SqlCommand();
  40. }
  41. private SqlCommand BatchCommand {
  42. get {
  43. SqlCommand command = _batchCommand;
  44. if (null == command) {
  45. throw ADP.ObjectDisposed(this);
  46. }
  47. return command;
  48. }
  49. }
  50. internal int CommandCount {
  51. get {
  52. return CommandList.Count;
  53. }
  54. }
  55. private List<LocalCommand> CommandList {
  56. get {
  57. List<LocalCommand> commandList = _commandList;
  58. if (null == commandList) {
  59. throw ADP.ObjectDisposed(this);
  60. }
  61. return commandList;
  62. }
  63. }
  64. internal int CommandTimeout {
  65. /*get {
  66. return BatchCommand.CommandTimeout;
  67. }*/
  68. set {
  69. BatchCommand.CommandTimeout = value;
  70. }
  71. }
  72. internal SqlConnection Connection {
  73. get {
  74. return BatchCommand.Connection;
  75. }
  76. set {
  77. BatchCommand.Connection = value;
  78. }
  79. }
  80. internal SqlTransaction Transaction {
  81. /*get {
  82. return BatchCommand.Transaction;
  83. }*/
  84. set {
  85. BatchCommand.Transaction = value;
  86. }
  87. }
  88. internal int ObjectID {
  89. get {
  90. return _objectID;
  91. }
  92. }
  93. internal void Append(SqlCommand command) {
  94. ADP.CheckArgumentNull(command, "command");
  95. Bid.Trace("<sc.SqlCommandSet.Append|API> %d#, command=%d, parameterCount=%d\n", ObjectID, command.ObjectID, command.Parameters.Count);
  96. string cmdText = command.CommandText;
  97. if (ADP.IsEmpty(cmdText)) {
  98. throw ADP.CommandTextRequired(ADP.Append);
  99. }
  100. CommandType commandType = command.CommandType;
  101. switch(commandType) {
  102. case CommandType.Text:
  103. case CommandType.StoredProcedure:
  104. break;
  105. case CommandType.TableDirect:
  106. Debug.Assert(false, "command.CommandType");
  107. throw System.Data.SqlClient.SQL.NotSupportedCommandType(commandType);
  108. default:
  109. Debug.Assert(false, "command.CommandType");
  110. throw ADP.InvalidCommandType(commandType);
  111. }
  112. SqlParameterCollection parameters = null;
  113. SqlParameterCollection collection = command.Parameters;
  114. if (0 < collection.Count) {
  115. parameters = new SqlParameterCollection();
  116. // clone parameters so they aren't destroyed
  117. for(int i = 0; i < collection.Count; ++i) {
  118. SqlParameter p = new SqlParameter();
  119. collection[i].CopyTo(p);
  120. parameters.Add(p);
  121. // SQL Injection awarene
  122. if (!SqlIdentifierParser.IsMatch(p.ParameterName)) {
  123. throw ADP.BadParameterName(p.ParameterName);
  124. }
  125. }
  126. foreach(SqlParameter p in parameters) {
  127. // deep clone the parameter value if byte[] or char[]
  128. object obj = p.Value;
  129. byte[] byteValues = (obj as byte[]);
  130. if (null != byteValues) {
  131. int offset = p.Offset;
  132. int size = p.Size;
  133. int countOfBytes = byteValues.Length - offset;
  134. if ((0 != size) && (size < countOfBytes)) {
  135. countOfBytes = size;
  136. }
  137. byte[] copy = new byte[Math.Max(countOfBytes, 0)];
  138. Buffer.BlockCopy(byteValues, offset, copy, 0, copy.Length);
  139. p.Offset = 0;
  140. p.Value = copy;
  141. }
  142. else {
  143. char[] charValues = (obj as char[]);
  144. if (null != charValues) {
  145. int offset = p.Offset;
  146. int size = p.Size;
  147. int countOfChars = charValues.Length - offset;
  148. if ((0 != size) && (size < countOfChars)) {
  149. countOfChars = size;
  150. }
  151. char[] copy = new char[Math.Max(countOfChars, 0)];
  152. Buffer.BlockCopy(charValues, offset, copy, 0, copy.Length*2);
  153. p.Offset = 0;
  154. p.Value = copy;
  155. }
  156. else {
  157. ICloneable cloneable = (obj as ICloneable);
  158. if (null != cloneable) {
  159. p.Value = cloneable.Clone();
  160. }
  161. }
  162. }
  163. }
  164. }
  165. int returnParameterIndex = -1;
  166. if (null != parameters) {
  167. for(int i = 0; i < parameters.Count; ++i) {
  168. if (ParameterDirection.ReturnValue == parameters[i].Direction) {
  169. returnParameterIndex = i;
  170. break;
  171. }
  172. }
  173. }
  174. LocalCommand cmd = new LocalCommand(cmdText, parameters, returnParameterIndex, command.CommandType);
  175. CommandList.Add(cmd);
  176. }
  177. internal static void BuildStoredProcedureName(StringBuilder builder, string part) {
  178. if ((null != part) && (0 < part.Length)) {
  179. if ('[' == part[0]) {
  180. int count = 0;
  181. foreach(char c in part) {
  182. if (']' == c) {
  183. count++;
  184. }
  185. }
  186. if (1 == (count%2)) {
  187. builder.Append(part);
  188. return;
  189. }
  190. }
  191. // the part is not escaped, escape it now
  192. SqlServerEscapeHelper.EscapeIdentifier(builder, part);
  193. }
  194. }
  195. internal void Clear() {
  196. Bid.Trace("<sc.SqlCommandSet.Clear|API> %d#\n", ObjectID);
  197. DbCommand batchCommand = BatchCommand;
  198. if (null != batchCommand) {
  199. batchCommand.Parameters.Clear();
  200. batchCommand.CommandText = null;
  201. }
  202. List<LocalCommand> commandList = _commandList;
  203. if (null != commandList) {
  204. commandList.Clear();
  205. }
  206. }
  207. internal void Dispose() {
  208. Bid.Trace("<sc.SqlCommandSet.Dispose|API> %d#\n", ObjectID);
  209. SqlCommand command = _batchCommand;
  210. _commandList = null;
  211. _batchCommand = null;
  212. if (null != command) {
  213. command.Dispose();
  214. }
  215. }
  216. internal int ExecuteNonQuery() {
  217. SqlConnection.ExecutePermission.Demand();
  218. IntPtr hscp;
  219. Bid.ScopeEnter(out hscp, "<sc.SqlCommandSet.ExecuteNonQuery|API> %d#", ObjectID);
  220. try {
  221. if (Connection.IsContextConnection) {
  222. throw SQL.BatchedUpdatesNotAvailableOnContextConnection();
  223. }
  224. ValidateCommandBehavior(ADP.ExecuteNonQuery, CommandBehavior.Default);
  225. BatchCommand.BatchRPCMode = true;
  226. BatchCommand.ClearBatchCommand();
  227. BatchCommand.Parameters.Clear();
  228. for (int ii = 0 ; ii < _commandList.Count; ii++) {
  229. LocalCommand cmd = _commandList[ii];
  230. BatchCommand.AddBatchCommand(cmd.CommandText, cmd.Parameters, cmd.CmdType);
  231. }
  232. return BatchCommand.ExecuteBatchRPCCommand();
  233. }
  234. finally {
  235. Bid.ScopeLeave(ref hscp);
  236. }
  237. }
  238. internal SqlParameter GetParameter(int commandIndex, int parameterIndex) {
  239. return CommandList[commandIndex].Parameters[parameterIndex];
  240. }
  241. internal bool GetBatchedAffected(int commandIdentifier, out int recordsAffected, out Exception error) {
  242. error = BatchCommand.GetErrors(commandIdentifier);
  243. int? affected = BatchCommand.GetRecordsAffected(commandIdentifier);
  244. recordsAffected = affected.GetValueOrDefault();
  245. return affected.HasValue;
  246. }
  247. internal int GetParameterCount(int commandIndex) {
  248. return CommandList[commandIndex].Parameters.Count;
  249. }
  250. private void ValidateCommandBehavior(string method, CommandBehavior behavior) {
  251. if (0 != (behavior & ~(CommandBehavior.SequentialAccess|CommandBehavior.CloseConnection))) {
  252. ADP.ValidateCommandBehavior(behavior);
  253. throw ADP.NotSupportedCommandBehavior(behavior & ~(CommandBehavior.SequentialAccess|CommandBehavior.CloseConnection), method);
  254. }
  255. }
  256. }
  257. }