SqlCommandBuilder.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. //
  2. // System.Data.SqlClient.SqlCommandBuilder.cs
  3. //
  4. // Author:
  5. // Tim Coleman ([email protected])
  6. //
  7. // Copyright (C) Tim Coleman, 2002
  8. //
  9. //
  10. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Collections;
  33. using System.ComponentModel;
  34. using System.Data;
  35. using System.Data.Common;
  36. using System.Text;
  37. namespace System.Data.SqlClient {
  38. #if NET_2_0
  39. public sealed class SqlCommandBuilder : DbCommandBuilder
  40. #else
  41. public sealed class SqlCommandBuilder : Component
  42. #endif // NET_2_0
  43. {
  44. #region Fields
  45. bool disposed = false;
  46. DataTable dbSchemaTable;
  47. SqlDataAdapter adapter;
  48. string quotePrefix;
  49. string quoteSuffix;
  50. string[] columnNames;
  51. string tableName;
  52. SqlCommand deleteCommand;
  53. SqlCommand insertCommand;
  54. SqlCommand updateCommand;
  55. // Used to construct WHERE clauses
  56. static readonly string clause1 = "({0} IS NULL AND {1} IS NULL)";
  57. static readonly string clause2 = "({0} = {1})";
  58. #endregion // Fields
  59. #region Constructors
  60. public SqlCommandBuilder ()
  61. {
  62. dbSchemaTable = null;
  63. adapter = null;
  64. quoteSuffix = String.Empty;
  65. quotePrefix = String.Empty;
  66. }
  67. public SqlCommandBuilder (SqlDataAdapter adapter)
  68. : this ()
  69. {
  70. DataAdapter = adapter;
  71. }
  72. #endregion // Constructors
  73. #region Properties
  74. [DataSysDescription ("The DataAdapter for which to automatically generate SqlCommands")]
  75. [DefaultValue (null)]
  76. public new SqlDataAdapter DataAdapter {
  77. get { return adapter; }
  78. set {
  79. if (adapter != null)
  80. adapter.RowUpdating -= new SqlRowUpdatingEventHandler (RowUpdatingHandler);
  81. adapter = value;
  82. if (adapter != null)
  83. adapter.RowUpdating += new SqlRowUpdatingEventHandler (RowUpdatingHandler);
  84. }
  85. }
  86. private string QuotedTableName {
  87. get { return GetQuotedString (tableName); }
  88. }
  89. [Browsable (false)]
  90. [DataSysDescription ("The character used in a text command as the opening quote for quoting identifiers that contain special characters.")]
  91. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  92. public
  93. #if NET_2_0
  94. override
  95. #endif // NET_2_0
  96. string QuotePrefix {
  97. get { return quotePrefix; }
  98. set {
  99. if (dbSchemaTable != null)
  100. throw new InvalidOperationException ("The QuotePrefix and QuoteSuffix properties cannot be changed once an Insert, Update, or Delete command has been generated.");
  101. quotePrefix = value;
  102. }
  103. }
  104. [Browsable (false)]
  105. [DataSysDescription ("The character used in a text command as the closing quote for quoting identifiers that contain special characters. ")]
  106. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  107. public
  108. #if NET_2_0
  109. override
  110. #endif // NET_2_0
  111. string QuoteSuffix {
  112. get { return quoteSuffix; }
  113. set {
  114. if (dbSchemaTable != null)
  115. throw new InvalidOperationException ("The QuotePrefix and QuoteSuffix properties cannot be changed once an Insert, Update, or Delete command has been generated.");
  116. quoteSuffix = value;
  117. }
  118. }
  119. private SqlCommand SourceCommand {
  120. get {
  121. if (adapter != null)
  122. return adapter.SelectCommand;
  123. return null;
  124. }
  125. }
  126. #endregion // Properties
  127. #region Methods
  128. private void BuildCache (bool closeConnection)
  129. {
  130. SqlCommand sourceCommand = SourceCommand;
  131. if (sourceCommand == null)
  132. throw new InvalidOperationException ("The DataAdapter.SelectCommand property needs to be initialized.");
  133. SqlConnection connection = sourceCommand.Connection;
  134. if (connection == null)
  135. throw new InvalidOperationException ("The DataAdapter.SelectCommand.Connection property needs to be initialized.");
  136. if (dbSchemaTable == null) {
  137. if (connection.State == ConnectionState.Open)
  138. closeConnection = false;
  139. else
  140. connection.Open ();
  141. SqlDataReader reader = sourceCommand.ExecuteReader (CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo);
  142. dbSchemaTable = reader.GetSchemaTable ();
  143. reader.Close ();
  144. if (closeConnection)
  145. connection.Close ();
  146. BuildInformation (dbSchemaTable);
  147. }
  148. }
  149. private void BuildInformation (DataTable schemaTable)
  150. {
  151. tableName = String.Empty;
  152. foreach (DataRow schemaRow in schemaTable.Rows) {
  153. if (schemaRow.IsNull ("BaseTableName") ||
  154. schemaRow ["BaseTableName"] == String.Empty)
  155. continue;
  156. if (tableName == String.Empty)
  157. tableName = (string) schemaRow ["BaseTableName"];
  158. else if (tableName != (string) schemaRow["BaseTableName"])
  159. throw new InvalidOperationException ("Dynamic SQL generation is not supported against multiple base tables.");
  160. }
  161. if (tableName == String.Empty)
  162. throw new InvalidOperationException ("Dynamic SQL generation is not supported with no base table.");
  163. dbSchemaTable = schemaTable;
  164. }
  165. private SqlCommand CreateDeleteCommand (DataRow row, DataTableMapping tableMapping)
  166. {
  167. // If no table was found, then we can't do an delete
  168. if (QuotedTableName == String.Empty)
  169. return null;
  170. CreateNewCommand (ref deleteCommand);
  171. string command = String.Format ("DELETE FROM {0} ", QuotedTableName);
  172. StringBuilder columns = new StringBuilder ();
  173. StringBuilder whereClause = new StringBuilder ();
  174. string dsColumnName = String.Empty;
  175. bool keyFound = false;
  176. int parmIndex = 1;
  177. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  178. if (!IncludedInWhereClause (schemaRow))
  179. continue;
  180. if (whereClause.Length > 0)
  181. whereClause.Append (" AND ");
  182. bool isKey = (bool) schemaRow ["IsKey"];
  183. SqlParameter parameter = null;
  184. if (!isKey) {
  185. parameter = deleteCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  186. parameter.SourceVersion = DataRowVersion.Original;
  187. dsColumnName = parameter.SourceColumn;
  188. if (tableMapping != null
  189. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  190. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  191. if (row != null)
  192. parameter.Value = row [dsColumnName, DataRowVersion.Original];
  193. whereClause.Append ("(");
  194. whereClause.Append (String.Format (clause1, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  195. whereClause.Append (" OR ");
  196. }
  197. else
  198. keyFound = true;
  199. parameter = deleteCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  200. parameter.SourceVersion = DataRowVersion.Original;
  201. dsColumnName = parameter.SourceColumn;
  202. if (tableMapping != null
  203. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  204. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  205. if (row != null)
  206. parameter.Value = row [dsColumnName, DataRowVersion.Original];
  207. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  208. if (!isKey)
  209. whereClause.Append (")");
  210. }
  211. if (!keyFound)
  212. throw new InvalidOperationException ("Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information.");
  213. // We're all done, so bring it on home
  214. string sql = String.Format ("{0} WHERE ( {1} )", command, whereClause.ToString ());
  215. deleteCommand.CommandText = sql;
  216. return deleteCommand;
  217. }
  218. private SqlCommand CreateInsertCommand (DataRow row, DataTableMapping tableMapping)
  219. {
  220. if (QuotedTableName == String.Empty)
  221. return null;
  222. CreateNewCommand (ref insertCommand);
  223. string command = String.Format ("INSERT INTO {0}", QuotedTableName);
  224. string sql;
  225. StringBuilder columns = new StringBuilder ();
  226. StringBuilder values = new StringBuilder ();
  227. string dsColumnName = String.Empty;
  228. int parmIndex = 1;
  229. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  230. if (!IncludedInInsert (schemaRow))
  231. continue;
  232. if (parmIndex > 1) {
  233. columns.Append (" , ");
  234. values.Append (" , ");
  235. }
  236. SqlParameter parameter = insertCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  237. parameter.SourceVersion = DataRowVersion.Current;
  238. dsColumnName = parameter.SourceColumn;
  239. if (tableMapping != null
  240. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  241. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  242. if (row != null)
  243. parameter.Value = row [dsColumnName];
  244. columns.Append (GetQuotedString (parameter.SourceColumn));
  245. values.Append (parameter.ParameterName);
  246. }
  247. sql = String.Format ("{0}( {1} ) VALUES ( {2} )", command, columns.ToString (), values.ToString ());
  248. insertCommand.CommandText = sql;
  249. return insertCommand;
  250. }
  251. private void CreateNewCommand (ref SqlCommand command)
  252. {
  253. SqlCommand sourceCommand = SourceCommand;
  254. if (command == null) {
  255. command = sourceCommand.Connection.CreateCommand ();
  256. command.CommandTimeout = sourceCommand.CommandTimeout;
  257. command.Transaction = sourceCommand.Transaction;
  258. }
  259. command.CommandType = CommandType.Text;
  260. command.UpdatedRowSource = UpdateRowSource.None;
  261. }
  262. private SqlCommand CreateUpdateCommand (DataRow row, DataTableMapping tableMapping)
  263. {
  264. // If no table was found, then we can't do an update
  265. if (QuotedTableName == String.Empty)
  266. return null;
  267. CreateNewCommand (ref updateCommand);
  268. string command = String.Format ("UPDATE {0} SET ", QuotedTableName);
  269. StringBuilder columns = new StringBuilder ();
  270. StringBuilder whereClause = new StringBuilder ();
  271. int parmIndex = 1;
  272. string dsColumnName = String.Empty;
  273. bool keyFound = false;
  274. // First, create the X=Y list for UPDATE
  275. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  276. if (columns.Length > 0)
  277. columns.Append (" , ");
  278. SqlParameter parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  279. parameter.SourceVersion = DataRowVersion.Current;
  280. dsColumnName = parameter.SourceColumn;
  281. if (tableMapping != null
  282. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  283. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  284. if (row != null)
  285. parameter.Value = row [dsColumnName];
  286. columns.Append (String.Format ("{0} = {1}", GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  287. }
  288. // Now, create the WHERE clause. This may be optimizable, but it would be ugly to incorporate
  289. // into the loop above. "Premature optimization is the root of all evil." -- Knuth
  290. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  291. if (!IncludedInWhereClause (schemaRow))
  292. continue;
  293. if (whereClause.Length > 0)
  294. whereClause.Append (" AND ");
  295. bool isKey = (bool) schemaRow ["IsKey"];
  296. SqlParameter parameter = null;
  297. if (!isKey) {
  298. parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  299. parameter.SourceVersion = DataRowVersion.Original;
  300. dsColumnName = parameter.SourceColumn;
  301. if (tableMapping != null
  302. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  303. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  304. if (row != null)
  305. parameter.Value = row [dsColumnName, DataRowVersion.Original];
  306. whereClause.Append ("(");
  307. whereClause.Append (String.Format (clause1, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  308. whereClause.Append (" OR ");
  309. }
  310. else
  311. keyFound = true;
  312. parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  313. parameter.SourceVersion = DataRowVersion.Original;
  314. dsColumnName = parameter.SourceColumn;
  315. if (tableMapping != null
  316. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  317. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  318. if (row != null)
  319. parameter.Value = row [dsColumnName, DataRowVersion.Original];
  320. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  321. if (!isKey)
  322. whereClause.Append (")");
  323. }
  324. if (!keyFound)
  325. throw new InvalidOperationException ("Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.");
  326. // We're all done, so bring it on home
  327. string sql = String.Format ("{0}{1} WHERE ( {2} )", command, columns.ToString (), whereClause.ToString ());
  328. updateCommand.CommandText = sql;
  329. return updateCommand;
  330. }
  331. private SqlParameter CreateParameter (int parmIndex, DataRow schemaRow)
  332. {
  333. string name = String.Format ("@p{0}", parmIndex);
  334. string sourceColumn = (string) schemaRow ["BaseColumnName"];
  335. SqlDbType sqlDbType = (SqlDbType) schemaRow ["ProviderType"];
  336. int size = (int) schemaRow ["ColumnSize"];
  337. return new SqlParameter (name, sqlDbType, size, sourceColumn);
  338. }
  339. public static void DeriveParameters (SqlCommand command)
  340. {
  341. command.DeriveParameters ();
  342. }
  343. protected override void Dispose (bool disposing)
  344. {
  345. if (!disposed) {
  346. if (disposing) {
  347. if (insertCommand != null)
  348. insertCommand.Dispose ();
  349. if (deleteCommand != null)
  350. deleteCommand.Dispose ();
  351. if (updateCommand != null)
  352. updateCommand.Dispose ();
  353. if (dbSchemaTable != null)
  354. dbSchemaTable.Dispose ();
  355. }
  356. disposed = true;
  357. }
  358. }
  359. public
  360. #if NET_2_0
  361. new
  362. #endif // NET_2_0
  363. SqlCommand GetDeleteCommand ()
  364. {
  365. BuildCache (true);
  366. return CreateDeleteCommand (null, null);
  367. }
  368. public
  369. #if NET_2_0
  370. new
  371. #endif // NET_2_0
  372. SqlCommand GetInsertCommand ()
  373. {
  374. BuildCache (true);
  375. return CreateInsertCommand (null, null);
  376. }
  377. private string GetQuotedString (string value)
  378. {
  379. if (value == String.Empty || value == null)
  380. return value;
  381. if (quotePrefix == String.Empty && quoteSuffix == String.Empty)
  382. return value;
  383. return String.Format ("{0}{1}{2}", quotePrefix, value, quoteSuffix);
  384. }
  385. public
  386. #if NET_2_0
  387. new
  388. #endif // NET_2_0
  389. SqlCommand GetUpdateCommand ()
  390. {
  391. BuildCache (true);
  392. return CreateUpdateCommand (null, null);
  393. }
  394. private bool IncludedInInsert (DataRow schemaRow)
  395. {
  396. // If the parameter has one of these properties, then we don't include it in the insert:
  397. // AutoIncrement, Hidden, Expression, RowVersion, ReadOnly
  398. if (!schemaRow.IsNull ("IsAutoIncrement") && (bool) schemaRow ["IsAutoIncrement"])
  399. return false;
  400. if (!schemaRow.IsNull ("IsHidden") && (bool) schemaRow ["IsHidden"])
  401. return false;
  402. if (!schemaRow.IsNull ("IsExpression") && (bool) schemaRow ["IsExpression"])
  403. return false;
  404. if (!schemaRow.IsNull ("IsRowVersion") && (bool) schemaRow ["IsRowVersion"])
  405. return false;
  406. if (!schemaRow.IsNull ("IsReadOnly") && (bool) schemaRow ["IsReadOnly"])
  407. return false;
  408. return true;
  409. }
  410. private bool IncludedInUpdate (DataRow schemaRow)
  411. {
  412. // If the parameter has one of these properties, then we don't include it in the insert:
  413. // AutoIncrement, Hidden, RowVersion
  414. if ((bool) schemaRow ["IsAutoIncrement"])
  415. return false;
  416. if ((bool) schemaRow ["IsHidden"])
  417. return false;
  418. if ((bool) schemaRow ["IsRowVersion"])
  419. return false;
  420. return true;
  421. }
  422. private bool IncludedInWhereClause (DataRow schemaRow)
  423. {
  424. if ((bool) schemaRow ["IsLong"])
  425. return false;
  426. return true;
  427. }
  428. [MonoTODO ("Figure out what else needs to be cleaned up when we refresh.")]
  429. public
  430. #if NET_2_0
  431. override
  432. #endif // NET_2_0
  433. void RefreshSchema ()
  434. {
  435. tableName = String.Empty;
  436. dbSchemaTable = null;
  437. }
  438. #if NET_2_0
  439. [MonoTODO]
  440. protected override void ApplyParameterInfo (IDbDataParameter dbParameter, DataRow row)
  441. {
  442. throw new NotImplementedException ();
  443. }
  444. [MonoTODO]
  445. protected override string GetParameterName (int position)
  446. {
  447. throw new NotImplementedException ();
  448. }
  449. [MonoTODO]
  450. protected override string GetParameterPlaceholder (int position)
  451. {
  452. throw new NotImplementedException ();
  453. }
  454. [MonoTODO]
  455. protected override DbProviderFactory ProviderFactory
  456. {
  457. get {throw new NotImplementedException ();}
  458. }
  459. #endif // NET_2_0
  460. #endregion // Methods
  461. #region Event Handlers
  462. private void RowUpdatingHandler (object sender, SqlRowUpdatingEventArgs args)
  463. {
  464. if (args.Command != null)
  465. return;
  466. try {
  467. switch (args.StatementType) {
  468. case StatementType.Insert:
  469. args.Command = GetInsertCommand ();
  470. break;
  471. case StatementType.Update:
  472. args.Command = GetUpdateCommand ();
  473. break;
  474. case StatementType.Delete:
  475. args.Command = GetDeleteCommand ();
  476. break;
  477. }
  478. } catch (Exception e) {
  479. args.Errors = e;
  480. args.Status = UpdateStatus.ErrorsOccurred;
  481. }
  482. }
  483. #if NET_2_0
  484. [MonoTODO]
  485. protected override void SetRowUpdatingHandler (DbDataAdapter adapter)
  486. {
  487. throw new NotImplementedException ();
  488. }
  489. #endif // NET_2_0
  490. #endregion // Event Handlers
  491. }
  492. }