You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

295 lines
11 KiB

4 years ago
  1. // Copyright ?2004, 2013, Oracle and/or its affiliates. All rights reserved.
  2. //
  3. // MySQL Connector/NET is licensed under the terms of the GPLv2
  4. // <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
  5. // MySQL Connectors. There are special exceptions to the terms and
  6. // conditions of the GPLv2 as it is applied to this software, see the
  7. // FLOSS License Exception
  8. // <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
  9. //
  10. // This program is free software; you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published
  12. // by the Free Software Foundation; version 2 of the License.
  13. //
  14. // This program is distributed in the hope that it will be useful, but
  15. // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  16. // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  17. // for more details.
  18. //
  19. // You should have received a copy of the GNU General Public License along
  20. // with this program; if not, write to the Free Software Foundation, Inc.,
  21. // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  22. #if MYSQL_6_9
  23. using System;
  24. using System.ComponentModel;
  25. using System.Data.Common;
  26. using System.Data;
  27. using System.Text;
  28. using Externals.MySql.Data.Common;
  29. using System.Collections;
  30. using Externals.MySql.Data.Types;
  31. using System.Globalization;
  32. using Externals.MySql.Data.MySqlClient.Properties;
  33. using System.Collections.Generic;
  34. namespace Externals.MySql.Data.MySqlClient
  35. {
  36. [ToolboxItem(false)]
  37. [System.ComponentModel.DesignerCategory("Code")]
  38. internal sealed class MySqlCommandBuilder : DbCommandBuilder
  39. {
  40. public MySqlCommandBuilder()
  41. {
  42. QuotePrefix = QuoteSuffix = "`";
  43. }
  44. public MySqlCommandBuilder(MySqlDataAdapter adapter)
  45. : this()
  46. {
  47. DataAdapter = adapter;
  48. }
  49. public new MySqlDataAdapter DataAdapter
  50. {
  51. get { return (MySqlDataAdapter)base.DataAdapter; }
  52. set { base.DataAdapter = value; }
  53. }
  54. #region Public Methods
  55. /// <summary>
  56. /// Retrieves parameter information from the stored procedure specified
  57. /// in the MySqlCommand and populates the Parameters collection of the
  58. /// specified MySqlCommand object.
  59. /// This method is not currently supported since stored procedures are
  60. /// not available in MySql.
  61. /// </summary>
  62. /// <param name="command">The MySqlCommand referencing the stored
  63. /// procedure from which the parameter information is to be derived.
  64. /// The derived parameters are added to the Parameters collection of the
  65. /// MySqlCommand.</param>
  66. /// <exception cref="InvalidOperationException">The command text is not
  67. /// a valid stored procedure name.</exception>
  68. public static void DeriveParameters(MySqlCommand command)
  69. {
  70. if (command.CommandType != CommandType.StoredProcedure)
  71. throw new InvalidOperationException(Resources.CanNotDeriveParametersForTextCommands);
  72. // retrieve the proc definition from the cache.
  73. string spName = command.CommandText;
  74. if (spName.IndexOf(".") == -1)
  75. spName = command.Connection.Database + "." + spName;
  76. try
  77. {
  78. ProcedureCacheEntry entry = command.Connection.ProcedureCache.GetProcedure(command.Connection, spName, null);
  79. command.Parameters.Clear();
  80. foreach (MySqlSchemaRow row in entry.parameters.Rows)
  81. {
  82. MySqlParameter p = new MySqlParameter();
  83. p.ParameterName = String.Format("@{0}", row["PARAMETER_NAME"]);
  84. if (row["ORDINAL_POSITION"].Equals(0) && p.ParameterName == "@")
  85. p.ParameterName = "@RETURN_VALUE";
  86. p.Direction = GetDirection(row);
  87. bool unsigned = StoredProcedure.GetFlags(row["DTD_IDENTIFIER"].ToString()).IndexOf("UNSIGNED") != -1;
  88. bool real_as_float = entry.procedure.Rows[0]["SQL_MODE"].ToString().IndexOf("REAL_AS_FLOAT") != -1;
  89. p.MySqlDbType = MetaData.NameToType(row["DATA_TYPE"].ToString(),
  90. unsigned, real_as_float, command.Connection);
  91. if (row["CHARACTER_MAXIMUM_LENGTH"] != null)
  92. p.Size = (int)row["CHARACTER_MAXIMUM_LENGTH"];
  93. if (row["NUMERIC_PRECISION"] != null)
  94. p.Precision = Convert.ToByte(row["NUMERIC_PRECISION"]);
  95. if (row["NUMERIC_SCALE"] != null)
  96. p.Scale = Convert.ToByte(row["NUMERIC_SCALE"]);
  97. if (p.MySqlDbType == MySqlDbType.Set || p.MySqlDbType == MySqlDbType.Enum)
  98. p.PossibleValues = GetPossibleValues(row);
  99. command.Parameters.Add(p);
  100. }
  101. }
  102. catch (InvalidOperationException ioe)
  103. {
  104. throw new MySqlException(Resources.UnableToDeriveParameters, ioe);
  105. }
  106. }
  107. private static List<string> GetPossibleValues(MySqlSchemaRow row)
  108. {
  109. string[] types = new string[] { "ENUM", "SET" };
  110. string dtdIdentifier = row["DTD_IDENTIFIER"].ToString().Trim();
  111. int index = 0;
  112. for (; index < 2; index++)
  113. if (dtdIdentifier.StartsWith(types[index], StringComparison.OrdinalIgnoreCase))
  114. break;
  115. if (index == 2) return null;
  116. dtdIdentifier = dtdIdentifier.Substring(types[index].Length).Trim();
  117. dtdIdentifier = dtdIdentifier.Trim('(', ')').Trim();
  118. List<string> values = new List<string>();
  119. MySqlTokenizer tokenzier = new MySqlTokenizer(dtdIdentifier);
  120. string token = tokenzier.NextToken();
  121. int start = tokenzier.StartIndex;
  122. while (true)
  123. {
  124. if (token == null || token == ",")
  125. {
  126. int end = dtdIdentifier.Length - 1;
  127. if (token == ",")
  128. end = tokenzier.StartIndex;
  129. string value = dtdIdentifier.Substring(start, end - start).Trim('\'', '\"').Trim();
  130. values.Add(value);
  131. start = tokenzier.StopIndex;
  132. }
  133. if (token == null) break;
  134. token = tokenzier.NextToken();
  135. }
  136. return values;
  137. }
  138. private static ParameterDirection GetDirection(MySqlSchemaRow row)
  139. {
  140. string mode = row["PARAMETER_MODE"].ToString();
  141. int ordinal = Convert.ToInt32(row["ORDINAL_POSITION"]);
  142. if (0 == ordinal)
  143. return ParameterDirection.ReturnValue;
  144. else if (mode == "IN")
  145. return ParameterDirection.Input;
  146. else if (mode == "OUT")
  147. return ParameterDirection.Output;
  148. return ParameterDirection.InputOutput;
  149. }
  150. /// <summary>
  151. /// Gets the delete command.
  152. /// </summary>
  153. /// <returns></returns>
  154. public new MySqlCommand GetDeleteCommand()
  155. {
  156. return (MySqlCommand)base.GetDeleteCommand();
  157. }
  158. /// <summary>
  159. /// Gets the update command.
  160. /// </summary>
  161. /// <returns></returns>
  162. public new MySqlCommand GetUpdateCommand()
  163. {
  164. return (MySqlCommand)base.GetUpdateCommand();
  165. }
  166. /// <summary>
  167. /// Gets the insert command.
  168. /// </summary>
  169. /// <returns></returns>
  170. public new MySqlCommand GetInsertCommand()
  171. {
  172. return (MySqlCommand)GetInsertCommand(false);
  173. }
  174. public override string QuoteIdentifier(string unquotedIdentifier)
  175. {
  176. if (unquotedIdentifier == null) throw new
  177. ArgumentNullException("unquotedIdentifier");
  178. // don't quote again if it is already quoted
  179. if (unquotedIdentifier.StartsWith(QuotePrefix) &&
  180. unquotedIdentifier.EndsWith(QuoteSuffix))
  181. return unquotedIdentifier;
  182. unquotedIdentifier = unquotedIdentifier.Replace(QuotePrefix, QuotePrefix + QuotePrefix);
  183. return String.Format("{0}{1}{2}", QuotePrefix, unquotedIdentifier, QuoteSuffix);
  184. }
  185. public override string UnquoteIdentifier(string quotedIdentifier)
  186. {
  187. if (quotedIdentifier == null) throw new
  188. ArgumentNullException("quotedIdentifier");
  189. // don't unquote again if it is already unquoted
  190. if (!quotedIdentifier.StartsWith(QuotePrefix) ||
  191. !quotedIdentifier.EndsWith(QuoteSuffix))
  192. return quotedIdentifier;
  193. if (quotedIdentifier.StartsWith(QuotePrefix))
  194. quotedIdentifier = quotedIdentifier.Substring(1);
  195. if (quotedIdentifier.EndsWith(QuoteSuffix))
  196. quotedIdentifier = quotedIdentifier.Substring(0, quotedIdentifier.Length - 1);
  197. quotedIdentifier = quotedIdentifier.Replace(QuotePrefix + QuotePrefix, QuotePrefix);
  198. return quotedIdentifier;
  199. }
  200. #endregion
  201. protected override DataTable GetSchemaTable(DbCommand sourceCommand)
  202. {
  203. DataTable schemaTable = base.GetSchemaTable(sourceCommand);
  204. foreach (DataRow row in schemaTable.Rows)
  205. if (row["BaseSchemaName"].Equals(sourceCommand.Connection.Database))
  206. row["BaseSchemaName"] = null;
  207. return schemaTable;
  208. }
  209. /// <summary>
  210. ///
  211. /// </summary>
  212. /// <param name="parameterName"></param>
  213. /// <returns></returns>
  214. protected override string GetParameterName(string parameterName)
  215. {
  216. StringBuilder sb = new StringBuilder(parameterName);
  217. sb.Replace(" ", "");
  218. sb.Replace("/", "_per_");
  219. sb.Replace("-", "_");
  220. sb.Replace(")", "_cb_");
  221. sb.Replace("(", "_ob_");
  222. sb.Replace("%", "_pct_");
  223. sb.Replace("<", "_lt_");
  224. sb.Replace(">", "_gt_");
  225. sb.Replace(".", "_pt_");
  226. return String.Format("@{0}", sb.ToString());
  227. }
  228. protected override void ApplyParameterInfo(DbParameter parameter, DataRow row,
  229. StatementType statementType, bool whereClause)
  230. {
  231. ((MySqlParameter)parameter).MySqlDbType = (MySqlDbType)row["ProviderType"];
  232. }
  233. protected override string GetParameterName(int parameterOrdinal)
  234. {
  235. return String.Format("@p{0}", parameterOrdinal.ToString(CultureInfo.InvariantCulture));
  236. }
  237. protected override string GetParameterPlaceholder(int parameterOrdinal)
  238. {
  239. return String.Format("@p{0}", parameterOrdinal.ToString(CultureInfo.InvariantCulture));
  240. }
  241. protected override void SetRowUpdatingHandler(DbDataAdapter adapter)
  242. {
  243. MySqlDataAdapter myAdapter = (adapter as MySqlDataAdapter);
  244. if (adapter != base.DataAdapter)
  245. myAdapter.RowUpdating += new MySqlRowUpdatingEventHandler(RowUpdating);
  246. else
  247. myAdapter.RowUpdating -= new MySqlRowUpdatingEventHandler(RowUpdating);
  248. }
  249. private void RowUpdating(object sender, MySqlRowUpdatingEventArgs args)
  250. {
  251. base.RowUpdatingHandler(args);
  252. }
  253. }
  254. }
  255. #endif