SqlCommandSet.cs 11 KB

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