SqlCommandBuilder.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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 (tableName == String.Empty)
  154. tableName = schemaRow.IsNull ("BaseTableName") ? null : (string) schemaRow ["BaseTableName"];
  155. else if (schemaRow.IsNull ("BaseTableName")) {
  156. if (tableName != null)
  157. throw new InvalidOperationException ("Dynamic SQL generation is not supported against multiple base tables.");
  158. } else if (tableName != (string) schemaRow["BaseTableName"])
  159. throw new InvalidOperationException ("Dynamic SQL generation is not supported against multiple base tables.");
  160. }
  161. dbSchemaTable = schemaTable;
  162. }
  163. private SqlCommand CreateDeleteCommand (DataRow row, DataTableMapping tableMapping)
  164. {
  165. // If no table was found, then we can't do an delete
  166. if (QuotedTableName == String.Empty)
  167. return null;
  168. CreateNewCommand (ref deleteCommand);
  169. string command = String.Format ("DELETE FROM {0} ", QuotedTableName);
  170. StringBuilder columns = new StringBuilder ();
  171. StringBuilder whereClause = new StringBuilder ();
  172. string dsColumnName = String.Empty;
  173. bool keyFound = false;
  174. int parmIndex = 1;
  175. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  176. if (!IncludedInWhereClause (schemaRow))
  177. continue;
  178. if (whereClause.Length > 0)
  179. whereClause.Append (" AND ");
  180. bool isKey = (bool) schemaRow ["IsKey"];
  181. SqlParameter parameter = null;
  182. if (!isKey) {
  183. parameter = deleteCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  184. dsColumnName = parameter.SourceColumn;
  185. if (tableMapping != null
  186. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  187. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  188. if (row != null)
  189. parameter.Value = row [dsColumnName, DataRowVersion.Original];
  190. whereClause.Append ("(");
  191. whereClause.Append (String.Format (clause1, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  192. whereClause.Append (" OR ");
  193. }
  194. else
  195. keyFound = true;
  196. parameter = deleteCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  197. dsColumnName = parameter.SourceColumn;
  198. if (tableMapping != null
  199. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  200. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  201. if (row != null)
  202. parameter.Value = row [dsColumnName, DataRowVersion.Original];
  203. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  204. if (!isKey)
  205. whereClause.Append (")");
  206. }
  207. if (!keyFound)
  208. throw new InvalidOperationException ("Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information.");
  209. // We're all done, so bring it on home
  210. string sql = String.Format ("{0} WHERE ( {1} )", command, whereClause.ToString ());
  211. deleteCommand.CommandText = sql;
  212. return deleteCommand;
  213. }
  214. private SqlCommand CreateInsertCommand (DataRow row, DataTableMapping tableMapping)
  215. {
  216. if (QuotedTableName == String.Empty)
  217. return null;
  218. CreateNewCommand (ref insertCommand);
  219. string command = String.Format ("INSERT INTO {0}", QuotedTableName);
  220. string sql;
  221. StringBuilder columns = new StringBuilder ();
  222. StringBuilder values = new StringBuilder ();
  223. string dsColumnName = String.Empty;
  224. int parmIndex = 1;
  225. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  226. if (!IncludedInInsert (schemaRow))
  227. continue;
  228. if (parmIndex > 1) {
  229. columns.Append (" , ");
  230. values.Append (" , ");
  231. }
  232. SqlParameter parameter = insertCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  233. dsColumnName = parameter.SourceColumn;
  234. if (tableMapping != null
  235. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  236. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  237. if (row != null)
  238. parameter.Value = row [dsColumnName];
  239. columns.Append (GetQuotedString (parameter.SourceColumn));
  240. values.Append (parameter.ParameterName);
  241. }
  242. sql = String.Format ("{0}( {1} ) VALUES ( {2} )", command, columns.ToString (), values.ToString ());
  243. insertCommand.CommandText = sql;
  244. return insertCommand;
  245. }
  246. private void CreateNewCommand (ref SqlCommand command)
  247. {
  248. SqlCommand sourceCommand = SourceCommand;
  249. if (command == null) {
  250. command = sourceCommand.Connection.CreateCommand ();
  251. command.CommandTimeout = sourceCommand.CommandTimeout;
  252. command.Transaction = sourceCommand.Transaction;
  253. }
  254. command.CommandType = CommandType.Text;
  255. command.UpdatedRowSource = UpdateRowSource.None;
  256. }
  257. private SqlCommand CreateUpdateCommand (DataRow row, DataTableMapping tableMapping)
  258. {
  259. // If no table was found, then we can't do an update
  260. if (QuotedTableName == String.Empty)
  261. return null;
  262. CreateNewCommand (ref updateCommand);
  263. string command = String.Format ("UPDATE {0} SET ", QuotedTableName);
  264. StringBuilder columns = new StringBuilder ();
  265. StringBuilder whereClause = new StringBuilder ();
  266. int parmIndex = 1;
  267. string dsColumnName = String.Empty;
  268. bool keyFound = false;
  269. // First, create the X=Y list for UPDATE
  270. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  271. if (columns.Length > 0)
  272. columns.Append (" , ");
  273. SqlParameter parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  274. dsColumnName = parameter.SourceColumn;
  275. if (tableMapping != null
  276. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  277. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  278. if (row != null)
  279. parameter.Value = row [dsColumnName];
  280. columns.Append (String.Format ("{0} = {1}", GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  281. }
  282. // Now, create the WHERE clause. This may be optimizable, but it would be ugly to incorporate
  283. // into the loop above. "Premature optimization is the root of all evil." -- Knuth
  284. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  285. if (!IncludedInWhereClause (schemaRow))
  286. continue;
  287. if (whereClause.Length > 0)
  288. whereClause.Append (" AND ");
  289. bool isKey = (bool) schemaRow ["IsKey"];
  290. SqlParameter parameter = null;
  291. if (!isKey) {
  292. parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  293. dsColumnName = parameter.SourceColumn;
  294. if (tableMapping != null
  295. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  296. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  297. if (row != null)
  298. parameter.Value = row [dsColumnName, DataRowVersion.Original];
  299. whereClause.Append ("(");
  300. whereClause.Append (String.Format (clause1, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  301. whereClause.Append (" OR ");
  302. }
  303. else
  304. keyFound = true;
  305. parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  306. dsColumnName = parameter.SourceColumn;
  307. if (tableMapping != null
  308. && tableMapping.ColumnMappings.Contains (parameter.SourceColumn))
  309. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  310. if (row != null)
  311. parameter.Value = row [dsColumnName, DataRowVersion.Original];
  312. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  313. if (!isKey)
  314. whereClause.Append (")");
  315. }
  316. if (!keyFound)
  317. throw new InvalidOperationException ("Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.");
  318. // We're all done, so bring it on home
  319. string sql = String.Format ("{0}{1} WHERE ( {2} )", command, columns.ToString (), whereClause.ToString ());
  320. updateCommand.CommandText = sql;
  321. return updateCommand;
  322. }
  323. private SqlParameter CreateParameter (int parmIndex, DataRow schemaRow)
  324. {
  325. string name = String.Format ("@p{0}", parmIndex);
  326. string sourceColumn = (string) schemaRow ["BaseColumnName"];
  327. SqlDbType sqlDbType = (SqlDbType) schemaRow ["ProviderType"];
  328. int size = (int) schemaRow ["ColumnSize"];
  329. return new SqlParameter (name, sqlDbType, size, sourceColumn);
  330. }
  331. public static void DeriveParameters (SqlCommand command)
  332. {
  333. command.DeriveParameters ();
  334. }
  335. protected override void Dispose (bool disposing)
  336. {
  337. if (!disposed) {
  338. if (disposing) {
  339. if (insertCommand != null)
  340. insertCommand.Dispose ();
  341. if (deleteCommand != null)
  342. deleteCommand.Dispose ();
  343. if (updateCommand != null)
  344. updateCommand.Dispose ();
  345. if (dbSchemaTable != null)
  346. dbSchemaTable.Dispose ();
  347. }
  348. disposed = true;
  349. }
  350. }
  351. public
  352. #if NET_2_0
  353. new
  354. #endif // NET_2_0
  355. SqlCommand GetDeleteCommand ()
  356. {
  357. BuildCache (true);
  358. return CreateDeleteCommand (null, null);
  359. }
  360. public
  361. #if NET_2_0
  362. new
  363. #endif // NET_2_0
  364. SqlCommand GetInsertCommand ()
  365. {
  366. BuildCache (true);
  367. return CreateInsertCommand (null, null);
  368. }
  369. private string GetQuotedString (string value)
  370. {
  371. if (value == String.Empty || value == null)
  372. return value;
  373. if (quotePrefix == String.Empty && quoteSuffix == String.Empty)
  374. return value;
  375. return String.Format ("{0}{1}{2}", quotePrefix, value, quoteSuffix);
  376. }
  377. public
  378. #if NET_2_0
  379. new
  380. #endif // NET_2_0
  381. SqlCommand GetUpdateCommand ()
  382. {
  383. BuildCache (true);
  384. return CreateUpdateCommand (null, null);
  385. }
  386. private bool IncludedInInsert (DataRow schemaRow)
  387. {
  388. // If the parameter has one of these properties, then we don't include it in the insert:
  389. // AutoIncrement, Hidden, Expression, RowVersion, ReadOnly
  390. if (!schemaRow.IsNull ("IsAutoIncrement") && (bool) schemaRow ["IsAutoIncrement"])
  391. return false;
  392. if (!schemaRow.IsNull ("IsHidden") && (bool) schemaRow ["IsHidden"])
  393. return false;
  394. if (!schemaRow.IsNull ("IsExpression") && (bool) schemaRow ["IsExpression"])
  395. return false;
  396. if (!schemaRow.IsNull ("IsRowVersion") && (bool) schemaRow ["IsRowVersion"])
  397. return false;
  398. if (!schemaRow.IsNull ("IsReadOnly") && (bool) schemaRow ["IsReadOnly"])
  399. return false;
  400. return true;
  401. }
  402. private bool IncludedInUpdate (DataRow schemaRow)
  403. {
  404. // If the parameter has one of these properties, then we don't include it in the insert:
  405. // AutoIncrement, Hidden, RowVersion
  406. if ((bool) schemaRow ["IsAutoIncrement"])
  407. return false;
  408. if ((bool) schemaRow ["IsHidden"])
  409. return false;
  410. if ((bool) schemaRow ["IsRowVersion"])
  411. return false;
  412. return true;
  413. }
  414. private bool IncludedInWhereClause (DataRow schemaRow)
  415. {
  416. if ((bool) schemaRow ["IsLong"])
  417. return false;
  418. return true;
  419. }
  420. [MonoTODO ("Figure out what else needs to be cleaned up when we refresh.")]
  421. public
  422. #if NET_2_0
  423. override
  424. #endif // NET_2_0
  425. void RefreshSchema ()
  426. {
  427. tableName = String.Empty;
  428. dbSchemaTable = null;
  429. }
  430. #if NET_2_0
  431. [MonoTODO]
  432. protected override void ApplyParameterInfo (IDbDataParameter dbParameter, DataRow row)
  433. {
  434. throw new NotImplementedException ();
  435. }
  436. [MonoTODO]
  437. protected override string GetParameterName (int position)
  438. {
  439. throw new NotImplementedException ();
  440. }
  441. [MonoTODO]
  442. protected override string GetParameterPlaceholder (int position)
  443. {
  444. throw new NotImplementedException ();
  445. }
  446. [MonoTODO]
  447. protected override DbProviderFactory ProviderFactory
  448. {
  449. get {throw new NotImplementedException ();}
  450. }
  451. #endif // NET_2_0
  452. #endregion // Methods
  453. #region Event Handlers
  454. private void RowUpdatingHandler (object sender, SqlRowUpdatingEventArgs e)
  455. {
  456. if (e.Status != UpdateStatus.Continue)
  457. return;
  458. switch (e.StatementType) {
  459. case StatementType.Delete:
  460. deleteCommand = e.Command;
  461. break;
  462. case StatementType.Insert:
  463. insertCommand = e.Command;
  464. break;
  465. case StatementType.Update:
  466. updateCommand = e.Command;
  467. break;
  468. default:
  469. return;
  470. }
  471. try {
  472. BuildCache (false);
  473. switch (e.StatementType) {
  474. case StatementType.Delete:
  475. e.Command = CreateDeleteCommand (e.Row, e.TableMapping);
  476. e.Status = UpdateStatus.Continue;
  477. break;
  478. case StatementType.Insert:
  479. e.Command = CreateInsertCommand (e.Row, e.TableMapping);
  480. e.Status = UpdateStatus.Continue;
  481. break;
  482. case StatementType.Update:
  483. e.Command = CreateUpdateCommand (e.Row, e.TableMapping);
  484. e.Status = UpdateStatus.Continue;
  485. break;
  486. }
  487. if (e.Command != null && e.Row != null) {
  488. if (e.StatementType != StatementType.Delete)
  489. e.Row.AcceptChanges ();
  490. e.Status = UpdateStatus.Continue;
  491. }
  492. }
  493. catch (Exception exception) {
  494. e.Errors = exception;
  495. e.Status = UpdateStatus.ErrorsOccurred;
  496. }
  497. }
  498. #if NET_2_0
  499. [MonoTODO]
  500. protected override void SetRowUpdatingHandler (DbDataAdapter adapter)
  501. {
  502. throw new NotImplementedException ();
  503. }
  504. #endif // NET_2_0
  505. #endregion // Event Handlers
  506. }
  507. }