SqlCommandBuilder.cs 18 KB

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