DbCommandBuilder.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. //
  2. // System.Data.Common.DbCommandBuilder
  3. //
  4. // Author:
  5. // Tim Coleman ([email protected])
  6. //
  7. // Copyright (C) Tim Coleman, 2003
  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. #if NET_2_0 || TARGET_JVM
  32. using System.ComponentModel;
  33. using System.Data;
  34. using System.Text;
  35. namespace System.Data.Common {
  36. public abstract class DbCommandBuilder : Component
  37. {
  38. bool _setAllValues = false;
  39. bool _disposed = false;
  40. DataTable _dbSchemaTable;
  41. DbDataAdapter _dbDataAdapter = null;
  42. private CatalogLocation _catalogLocation = CatalogLocation.Start;
  43. private ConflictOption _conflictOption;
  44. private string _tableName;
  45. private string _catalogSeperator = ".";
  46. private string _quotePrefix;
  47. private string _quoteSuffix;
  48. private string _schemaSeperator = ".";
  49. private DbCommand _dbCommand;
  50. // Used to construct WHERE clauses
  51. static readonly string clause1 = "({0} = 1 AND {1} IS NULL)";
  52. static readonly string clause2 = "({0} = {1})";
  53. DbCommand _deleteCommand;
  54. DbCommand _insertCommand;
  55. DbCommand _updateCommand;
  56. #region Constructors
  57. protected DbCommandBuilder ()
  58. {
  59. }
  60. #endregion // Constructors
  61. #region Properties
  62. private void BuildCache (bool closeConnection)
  63. {
  64. DbCommand sourceCommand = SourceCommand;
  65. if (sourceCommand == null)
  66. throw new InvalidOperationException ("The DataAdapter.SelectCommand property needs to be initialized.");
  67. DbConnection connection = sourceCommand.Connection;
  68. if (connection == null)
  69. throw new InvalidOperationException ("The DataAdapter.SelectCommand.Connection property needs to be initialized.");
  70. if (_dbSchemaTable == null) {
  71. if (connection.State == ConnectionState.Open)
  72. closeConnection = false;
  73. else
  74. connection.Open ();
  75. DbDataReader reader = sourceCommand.ExecuteReader (CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo);
  76. _dbSchemaTable = reader.GetSchemaTable ();
  77. reader.Close ();
  78. if (closeConnection)
  79. connection.Close ();
  80. BuildInformation (_dbSchemaTable);
  81. }
  82. }
  83. private string QuotedTableName {
  84. get { return GetQuotedString (_tableName); }
  85. }
  86. private string GetQuotedString (string value)
  87. {
  88. if (value == String.Empty || value == null)
  89. return value;
  90. if (_quotePrefix == String.Empty && _quoteSuffix == String.Empty)
  91. return value;
  92. return String.Format ("{0}{1}{2}", _quotePrefix, value, _quoteSuffix);
  93. }
  94. private void BuildInformation (DataTable schemaTable)
  95. {
  96. _tableName = String.Empty;
  97. foreach (DataRow schemaRow in schemaTable.Rows) {
  98. if (schemaRow.IsNull ("BaseTableName") || (string) schemaRow ["BaseTableName"] == String.Empty)
  99. continue;
  100. if (_tableName == String.Empty)
  101. _tableName = (string) schemaRow ["BaseTableName"];
  102. else if (_tableName != (string) schemaRow["BaseTableName"])
  103. throw new InvalidOperationException ("Dynamic SQL generation is not supported against multiple base tables.");
  104. }
  105. if (_tableName == String.Empty)
  106. throw new InvalidOperationException ("Dynamic SQL generation is not supported with no base table.");
  107. _dbSchemaTable = schemaTable;
  108. }
  109. private bool IncludedInInsert (DataRow schemaRow)
  110. {
  111. // If the parameter has one of these properties, then we don't include it in the insert:
  112. // AutoIncrement, Hidden, Expression, RowVersion, ReadOnly
  113. if (!schemaRow.IsNull ("IsAutoIncrement") && (bool) schemaRow ["IsAutoIncrement"])
  114. return false;
  115. // if (!schemaRow.IsNull ("IsHidden") && (bool) schemaRow ["IsHidden"])
  116. // return false;
  117. if (!schemaRow.IsNull ("IsExpression") && (bool) schemaRow ["IsExpression"])
  118. return false;
  119. if (!schemaRow.IsNull ("IsRowVersion") && (bool) schemaRow ["IsRowVersion"])
  120. return false;
  121. if (!schemaRow.IsNull ("IsReadOnly") && (bool) schemaRow ["IsReadOnly"])
  122. return false;
  123. return true;
  124. }
  125. private bool IncludedInUpdate (DataRow schemaRow)
  126. {
  127. // If the parameter has one of these properties, then we don't include it in the insert:
  128. // AutoIncrement, Hidden, RowVersion
  129. if (!schemaRow.IsNull ("IsAutoIncrement") && (bool) schemaRow ["IsAutoIncrement"])
  130. return false;
  131. // if (!schemaRow.IsNull ("IsHidden") && (bool) schemaRow ["IsHidden"])
  132. // return false;
  133. if (!schemaRow.IsNull ("IsRowVersion") && (bool) schemaRow ["IsRowVersion"])
  134. return false;
  135. if (!schemaRow.IsNull ("IsExpression") && (bool) schemaRow ["IsExpression"])
  136. return false;
  137. if (!schemaRow.IsNull ("IsReadOnly") && (bool) schemaRow ["IsReadOnly"])
  138. return false;
  139. return true;
  140. }
  141. private bool IncludedInWhereClause (DataRow schemaRow)
  142. {
  143. if ((bool) schemaRow ["IsLong"])
  144. return false;
  145. return true;
  146. }
  147. private DbCommand CreateDeleteCommand (bool option)
  148. {
  149. // If no table was found, then we can't do an delete
  150. if (QuotedTableName == String.Empty)
  151. return null;
  152. CreateNewCommand (ref _deleteCommand);
  153. string command = String.Format ("DELETE FROM {0}", QuotedTableName);
  154. StringBuilder columns = new StringBuilder ();
  155. StringBuilder whereClause = new StringBuilder ();
  156. string dsColumnName = String.Empty;
  157. bool keyFound = false;
  158. int parmIndex = 1;
  159. foreach (DataRow schemaRow in _dbSchemaTable.Rows) {
  160. if ((bool)schemaRow["IsExpression"] == true)
  161. continue;
  162. if (!IncludedInWhereClause (schemaRow))
  163. continue;
  164. if (whereClause.Length > 0)
  165. whereClause.Append (" AND ");
  166. bool isKey = (bool) schemaRow ["IsKey"];
  167. DbParameter parameter = null;
  168. if (isKey)
  169. keyFound = true;
  170. //ms.net 1.1 generates the null check for columns even if AllowDBNull is false
  171. //while ms.net 2.0 does not. Anyways, since both forms are logically equivalent
  172. //following the 2.0 approach
  173. bool allowNull = (bool) schemaRow ["AllowDBNull"];
  174. if (!isKey && allowNull) {
  175. parameter = _deleteCommand.CreateParameter ();
  176. if (option) {
  177. parameter.ParameterName = String.Format ("@{0}",
  178. schemaRow ["BaseColumnName"]);
  179. } else {
  180. parameter.ParameterName = String.Format ("@p{0}", parmIndex++);
  181. }
  182. String sourceColumnName = (string) schemaRow ["BaseColumnName"];
  183. parameter.Value = 1;
  184. whereClause.Append ("(");
  185. whereClause.Append (String.Format (clause1, parameter.ParameterName,
  186. GetQuotedString (sourceColumnName)));
  187. whereClause.Append (" OR ");
  188. }
  189. int index = 0;
  190. if (option) {
  191. index = CreateParameter (_deleteCommand, schemaRow);
  192. } else {
  193. index = CreateParameter (_deleteCommand, parmIndex++, schemaRow);
  194. }
  195. parameter = _deleteCommand.Parameters [index];
  196. parameter.SourceVersion = DataRowVersion.Original;
  197. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  198. if (!isKey && allowNull)
  199. whereClause.Append (")");
  200. }
  201. if (!keyFound)
  202. throw new InvalidOperationException ("Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information.");
  203. // We're all done, so bring it on home
  204. string sql = String.Format ("{0} WHERE ({1})", command, whereClause.ToString ());
  205. _deleteCommand.CommandText = sql;
  206. return _deleteCommand;
  207. }
  208. private DbCommand CreateInsertCommand (bool option)
  209. {
  210. if (QuotedTableName == String.Empty)
  211. return null;
  212. CreateNewCommand (ref _insertCommand);
  213. string command = String.Format ("INSERT INTO {0}", QuotedTableName);
  214. string sql;
  215. StringBuilder columns = new StringBuilder ();
  216. StringBuilder values = new StringBuilder ();
  217. string dsColumnName = String.Empty;
  218. int parmIndex = 1;
  219. foreach (DataRow schemaRow in _dbSchemaTable.Rows) {
  220. if (!IncludedInInsert (schemaRow))
  221. continue;
  222. if (parmIndex > 1) {
  223. columns.Append (", ");
  224. values.Append (", ");
  225. }
  226. int index = -1;
  227. if (option) {
  228. index = CreateParameter (_insertCommand, schemaRow);
  229. } else {
  230. index = CreateParameter (_insertCommand, parmIndex++, schemaRow);
  231. }
  232. DbParameter parameter = _insertCommand.Parameters [index];
  233. parameter.SourceVersion = DataRowVersion.Current;
  234. columns.Append (GetQuotedString (parameter.SourceColumn));
  235. values.Append (parameter.ParameterName);
  236. }
  237. sql = String.Format ("{0} ({1}) VALUES ({2})", command, columns.ToString (), values.ToString ());
  238. _insertCommand.CommandText = sql;
  239. return _insertCommand;
  240. }
  241. private void CreateNewCommand (ref DbCommand command)
  242. {
  243. DbCommand sourceCommand = SourceCommand;
  244. if (command == null) {
  245. command = sourceCommand.Connection.CreateCommand ();
  246. command.CommandTimeout = sourceCommand.CommandTimeout;
  247. command.Transaction = sourceCommand.Transaction;
  248. }
  249. command.CommandType = CommandType.Text;
  250. command.UpdatedRowSource = UpdateRowSource.None;
  251. command.Parameters.Clear ();
  252. }
  253. private DbCommand CreateUpdateCommand (bool option)
  254. {
  255. // If no table was found, then we can't do an update
  256. if (QuotedTableName == String.Empty)
  257. return null;
  258. CreateNewCommand (ref _updateCommand);
  259. string command = String.Format ("UPDATE {0} SET ", QuotedTableName);
  260. StringBuilder columns = new StringBuilder ();
  261. StringBuilder whereClause = new StringBuilder ();
  262. int parmIndex = 1;
  263. string dsColumnName = String.Empty;
  264. bool keyFound = false;
  265. // First, create the X=Y list for UPDATE
  266. foreach (DataRow schemaRow in _dbSchemaTable.Rows) {
  267. if (!IncludedInUpdate (schemaRow))
  268. continue;
  269. if (columns.Length > 0)
  270. columns.Append (", ");
  271. int index = -1;
  272. if (option) {
  273. index = CreateParameter (_updateCommand, schemaRow);
  274. } else {
  275. index = CreateParameter (_updateCommand, parmIndex++, schemaRow);
  276. }
  277. DbParameter parameter = _updateCommand.Parameters [index];
  278. parameter.SourceVersion = DataRowVersion.Current;
  279. columns.Append (String.Format ("{0} = {1}", GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  280. }
  281. // Now, create the WHERE clause. This may be optimizable, but it would be ugly to incorporate
  282. // into the loop above. "Premature optimization is the root of all evil." -- Knuth
  283. foreach (DataRow schemaRow in _dbSchemaTable.Rows) {
  284. if ((bool) schemaRow ["IsExpression"] == true)
  285. continue;
  286. if (!IncludedInWhereClause (schemaRow))
  287. continue;
  288. if (whereClause.Length > 0)
  289. whereClause.Append (" AND ");
  290. bool isKey = (bool) schemaRow ["IsKey"];
  291. DbParameter parameter = null;
  292. if (isKey)
  293. keyFound = true;
  294. //ms.net 1.1 generates the null check for columns even if AllowDBNull is false
  295. //while ms.net 2.0 does not. Anyways, since both forms are logically equivalent
  296. //following the 2.0 approach
  297. bool allowNull = (bool) schemaRow ["AllowDBNull"];
  298. int index;
  299. if (!isKey && allowNull) {
  300. parameter = _updateCommand.CreateParameter ();
  301. if (option) {
  302. parameter.ParameterName = String.Format ("@{0}",
  303. schemaRow ["BaseColumnName"]);
  304. } else {
  305. parameter.ParameterName = String.Format ("@p{0}", parmIndex++);
  306. }
  307. parameter.Value = 1;
  308. whereClause.Append ("(");
  309. whereClause.Append (String.Format (clause1, parameter.ParameterName,
  310. GetQuotedString ((string) schemaRow ["BaseColumnName"])));
  311. whereClause.Append (" OR ");
  312. }
  313. if (option) {
  314. index = CreateParameter (_updateCommand, schemaRow);
  315. } else {
  316. index = CreateParameter (_updateCommand, parmIndex++, schemaRow);
  317. }
  318. parameter = _updateCommand.Parameters [index];
  319. parameter.SourceVersion = DataRowVersion.Original;
  320. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  321. if (!isKey && allowNull)
  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 int CreateParameter (DbCommand _dbCommand, int parmIndex, DataRow schemaRow)
  332. {
  333. DbParameter parameter = _dbCommand.CreateParameter ();
  334. parameter.ParameterName = String.Format ("@p{0}", parmIndex);
  335. parameter.SourceColumn = (string) schemaRow ["BaseColumnName"];
  336. parameter.Size = (int) schemaRow ["ColumnSize"];
  337. return _dbCommand.Parameters.Add (parameter);
  338. }
  339. private int CreateParameter (DbCommand _dbCommand, DataRow schemaRow)
  340. {
  341. DbParameter parameter = _dbCommand.CreateParameter ();
  342. parameter.ParameterName = String.Format ("@{0}",
  343. schemaRow ["BaseColumnName"]);
  344. parameter.SourceColumn = (string) schemaRow ["BaseColumnName"];
  345. parameter.Size = (int) schemaRow ["ColumnSize"];
  346. return _dbCommand.Parameters.Add (parameter);
  347. }
  348. [DefaultValue (CatalogLocation.Start)]
  349. public virtual CatalogLocation CatalogLocation {
  350. get { return _catalogLocation; }
  351. set { _catalogLocation = value; }
  352. }
  353. [DefaultValue (".")]
  354. public virtual string CatalogSeparator {
  355. get { return _catalogSeperator; }
  356. set { if (value != null) _catalogSeperator = value; }
  357. }
  358. [DefaultValue (ConflictOption.CompareAllSearchableValues)]
  359. public virtual ConflictOption ConflictOption {
  360. get { return _conflictOption; }
  361. set { _conflictOption = value; }
  362. }
  363. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  364. [Browsable (false)]
  365. public DbDataAdapter DataAdapter {
  366. get { return _dbDataAdapter; }
  367. set { if (value != null) _dbDataAdapter = value; }
  368. }
  369. [DefaultValue ("")]
  370. public virtual string QuotePrefix {
  371. get { return _quotePrefix; }
  372. set { if (value != null) _quotePrefix = value; }
  373. }
  374. [DefaultValue ("")]
  375. public virtual string QuoteSuffix {
  376. get { return _quoteSuffix; }
  377. set { if (value != null) _quoteSuffix = value; }
  378. }
  379. [DefaultValue (".")]
  380. public virtual string SchemaSeparator {
  381. get { return _schemaSeperator; }
  382. set { if (value != null) _schemaSeperator = value; }
  383. }
  384. [DefaultValue (false)]
  385. public bool SetAllValues {
  386. get { return _setAllValues; }
  387. set { _setAllValues = value; }
  388. }
  389. private DbCommand SourceCommand {
  390. get {
  391. if (_dbDataAdapter != null)
  392. return _dbDataAdapter.SelectCommand;
  393. return null;
  394. }
  395. }
  396. #endregion // Properties
  397. #region Methods
  398. protected abstract void ApplyParameterInfo (DbParameter parameter,
  399. DataRow row,
  400. StatementType statementType,
  401. bool whereClause);
  402. protected override void Dispose (bool disposing)
  403. {
  404. if (!_disposed) {
  405. if (disposing) {
  406. if (_insertCommand != null)
  407. _insertCommand.Dispose ();
  408. if (_deleteCommand != null)
  409. _deleteCommand.Dispose ();
  410. if (_updateCommand != null)
  411. _updateCommand.Dispose ();
  412. if (_dbSchemaTable != null)
  413. _dbSchemaTable.Dispose ();
  414. }
  415. _disposed = true;
  416. }
  417. }
  418. public DbCommand GetDeleteCommand ()
  419. {
  420. BuildCache (true);
  421. if (_deleteCommand == null)
  422. return CreateDeleteCommand (false);
  423. return _deleteCommand;
  424. }
  425. public DbCommand GetDeleteCommand (bool option)
  426. {
  427. BuildCache (true);
  428. if (_deleteCommand == null)
  429. return CreateDeleteCommand (option);
  430. return _deleteCommand;
  431. }
  432. public DbCommand GetInsertCommand ()
  433. {
  434. BuildCache (true);
  435. if (_insertCommand == null)
  436. return CreateInsertCommand (false);
  437. return _insertCommand;
  438. }
  439. public DbCommand GetInsertCommand (bool option)
  440. {
  441. BuildCache (true);
  442. if (_insertCommand == null)
  443. return CreateInsertCommand (option);
  444. return _insertCommand;
  445. }
  446. public DbCommand GetUpdateCommand ()
  447. {
  448. BuildCache (true);
  449. if (_updateCommand == null)
  450. return CreateUpdateCommand (false);
  451. return _updateCommand;
  452. }
  453. public DbCommand GetUpdateCommand (bool option)
  454. {
  455. BuildCache (true);
  456. if (_updateCommand == null)
  457. return CreateUpdateCommand (option);
  458. return _updateCommand;
  459. }
  460. [MonoTODO]
  461. protected virtual DbCommand InitializeCommand (DbCommand command)
  462. {
  463. throw new NotImplementedException ();
  464. }
  465. public virtual string QuoteIdentifier (string unquotedIdentifier)
  466. {
  467. if (unquotedIdentifier == null) {
  468. throw new ArgumentNullException("Unquoted identifier parameter cannot be null");
  469. }
  470. return String.Format ("{0}{1}{2}", this.QuotePrefix, unquotedIdentifier, this.QuoteSuffix);
  471. }
  472. public virtual string UnquoteIdentifier (string quotedIdentifier)
  473. {
  474. if (quotedIdentifier == null) {
  475. throw new ArgumentNullException ("Quoted identifier parameter cannot be null");
  476. }
  477. string unquotedIdentifier = quotedIdentifier.Trim ();
  478. if (unquotedIdentifier.StartsWith (this.QuotePrefix)) {
  479. unquotedIdentifier = unquotedIdentifier.Remove (0, 1);
  480. }
  481. if (unquotedIdentifier.EndsWith (this.QuoteSuffix)) {
  482. unquotedIdentifier = unquotedIdentifier.Remove (unquotedIdentifier.Length - 1, 1);
  483. }
  484. return unquotedIdentifier;
  485. }
  486. public virtual void RefreshSchema ()
  487. {
  488. _tableName = String.Empty;
  489. _dbSchemaTable = null;
  490. CreateNewCommand (ref _deleteCommand);
  491. CreateNewCommand (ref _updateCommand);
  492. CreateNewCommand (ref _insertCommand);
  493. }
  494. protected void RowUpdatingHandler (RowUpdatingEventArgs args)
  495. {
  496. if (args.Command != null)
  497. return;
  498. try {
  499. switch (args.StatementType) {
  500. case StatementType.Insert:
  501. args.Command = GetInsertCommand ();
  502. break;
  503. case StatementType.Update:
  504. args.Command = GetUpdateCommand ();
  505. break;
  506. case StatementType.Delete:
  507. args.Command = GetDeleteCommand ();
  508. break;
  509. }
  510. } catch (Exception e) {
  511. args.Errors = e;
  512. args.Status = UpdateStatus.ErrorsOccurred;
  513. }
  514. }
  515. protected abstract string GetParameterName (int parameterOrdinal);
  516. protected abstract string GetParameterName (String parameterName);
  517. protected abstract string GetParameterPlaceholder (int parameterOrdinal);
  518. protected abstract void SetRowUpdatingHandler (DbDataAdapter adapter);
  519. protected virtual DataTable GetSchemaTable (DbCommand cmd)
  520. {
  521. using (DbDataReader rdr = cmd.ExecuteReader ())
  522. return rdr.GetSchemaTable ();
  523. }
  524. #endregion // Methods
  525. }
  526. }
  527. #endif