SqlCommandBuilder.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. #if NET_2_0
  53. string _catalogSeperator = ".";
  54. string _schemaSeperator = ".";
  55. CatalogLocation _catalogLocation = CatalogLocation.Start;
  56. #endif
  57. SqlCommand deleteCommand;
  58. SqlCommand insertCommand;
  59. SqlCommand updateCommand;
  60. // Used to construct WHERE clauses
  61. static readonly string clause1 = "({0} = 1 AND {1} IS NULL)";
  62. static readonly string clause2 = "({0} = {1})";
  63. private SqlRowUpdatingEventHandler rowUpdatingHandler;
  64. #endregion // Fields
  65. #region Constructors
  66. public SqlCommandBuilder ()
  67. {
  68. dbSchemaTable = null;
  69. adapter = null;
  70. #if NET_2_0
  71. quoteSuffix = "]";
  72. quotePrefix = "[";
  73. #else
  74. quoteSuffix = String.Empty;
  75. quotePrefix = String.Empty;
  76. #endif
  77. }
  78. public SqlCommandBuilder (SqlDataAdapter adapter)
  79. : this ()
  80. {
  81. DataAdapter = adapter;
  82. }
  83. #endregion // Constructors
  84. #region Properties
  85. #if !NET_2_0
  86. [DataSysDescription ("The DataAdapter for which to automatically generate SqlCommands")]
  87. #endif
  88. [DefaultValue (null)]
  89. public new SqlDataAdapter DataAdapter {
  90. get { return adapter; }
  91. set {
  92. if (adapter != null)
  93. adapter.RowUpdating -= new SqlRowUpdatingEventHandler (RowUpdatingHandler);
  94. adapter = value;
  95. if (adapter != null)
  96. adapter.RowUpdating += new SqlRowUpdatingEventHandler (RowUpdatingHandler);
  97. }
  98. }
  99. private string QuotedTableName {
  100. get { return GetQuotedString (tableName); }
  101. }
  102. [Browsable (false)]
  103. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  104. #if !NET_2_0
  105. [DataSysDescription ("The character used in a text command as the opening quote for quoting identifiers that contain special characters.")]
  106. #else
  107. [EditorBrowsable (EditorBrowsableState.Never)]
  108. #endif // NET_2_0
  109. public
  110. #if NET_2_0
  111. override
  112. #endif // NET_2_0
  113. string QuotePrefix {
  114. get { return quotePrefix; }
  115. set {
  116. if (dbSchemaTable != null)
  117. throw new InvalidOperationException ("The QuotePrefix and QuoteSuffix properties cannot be changed once an Insert, Update, or Delete command has been generated.");
  118. quotePrefix = value;
  119. }
  120. }
  121. [Browsable (false)]
  122. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  123. #if !NET_2_0
  124. [DataSysDescription ("The character used in a text command as the closing quote for quoting identifiers that contain special characters. ")]
  125. #else
  126. [EditorBrowsable (EditorBrowsableState.Never)]
  127. #endif // NET_2_0
  128. public
  129. #if NET_2_0
  130. override
  131. #endif // NET_2_0
  132. string QuoteSuffix {
  133. get { return quoteSuffix; }
  134. set {
  135. if (dbSchemaTable != null)
  136. throw new InvalidOperationException ("The QuotePrefix and QuoteSuffix properties cannot be changed once an Insert, Update, or Delete command has been generated.");
  137. quoteSuffix = value;
  138. }
  139. }
  140. #if NET_2_0
  141. [EditorBrowsable (EditorBrowsableState.Never)]
  142. [Browsable (false)]
  143. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  144. #if !NET_2_0
  145. [DefaultValue (".")]
  146. #endif
  147. public override string CatalogSeparator {
  148. get { return _catalogSeperator; }
  149. set { if (value != null) _catalogSeperator = value; }
  150. }
  151. [EditorBrowsable (EditorBrowsableState.Never)]
  152. [Browsable (false)]
  153. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  154. #if !NET_2_0
  155. [DefaultValue (".")]
  156. #endif
  157. public override string SchemaSeparator {
  158. get { return _schemaSeperator; }
  159. set { if (value != null) _schemaSeperator = value; }
  160. }
  161. [EditorBrowsable (EditorBrowsableState.Never)]
  162. [Browsable (false)]
  163. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  164. #if !NET_2_0
  165. [DefaultValue (CatalogLocation.Start)]
  166. #endif
  167. public override CatalogLocation CatalogLocation {
  168. get { return _catalogLocation; }
  169. set { _catalogLocation = value; }
  170. }
  171. #endif // NET_2_0
  172. private SqlCommand SourceCommand {
  173. get {
  174. if (adapter != null)
  175. return adapter.SelectCommand;
  176. return null;
  177. }
  178. }
  179. #endregion // Properties
  180. #region Methods
  181. private void BuildCache (bool closeConnection)
  182. {
  183. SqlCommand sourceCommand = SourceCommand;
  184. if (sourceCommand == null)
  185. throw new InvalidOperationException ("The DataAdapter.SelectCommand property needs to be initialized.");
  186. SqlConnection connection = sourceCommand.Connection;
  187. if (connection == null)
  188. throw new InvalidOperationException ("The DataAdapter.SelectCommand.Connection property needs to be initialized.");
  189. if (dbSchemaTable == null) {
  190. if (connection.State == ConnectionState.Open)
  191. closeConnection = false;
  192. else
  193. connection.Open ();
  194. SqlDataReader reader = sourceCommand.ExecuteReader (CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo);
  195. dbSchemaTable = reader.GetSchemaTable ();
  196. reader.Close ();
  197. if (closeConnection)
  198. connection.Close ();
  199. BuildInformation (dbSchemaTable);
  200. }
  201. }
  202. private void BuildInformation (DataTable schemaTable)
  203. {
  204. tableName = String.Empty;
  205. foreach (DataRow schemaRow in schemaTable.Rows) {
  206. if (schemaRow.IsNull ("BaseTableName") ||
  207. (string) schemaRow ["BaseTableName"] == String.Empty)
  208. continue;
  209. if (tableName == String.Empty)
  210. tableName = (string) schemaRow ["BaseTableName"];
  211. else if (tableName != (string) schemaRow["BaseTableName"])
  212. throw new InvalidOperationException ("Dynamic SQL generation is not supported against multiple base tables.");
  213. }
  214. if (tableName == String.Empty)
  215. throw new InvalidOperationException ("Dynamic SQL generation is not supported with no base table.");
  216. dbSchemaTable = schemaTable;
  217. }
  218. private SqlCommand CreateDeleteCommand (bool option)
  219. {
  220. // If no table was found, then we can't do an delete
  221. if (QuotedTableName == String.Empty)
  222. return null;
  223. CreateNewCommand (ref deleteCommand);
  224. string command = String.Format ("DELETE FROM {0}", QuotedTableName);
  225. StringBuilder columns = new StringBuilder ();
  226. StringBuilder whereClause = new StringBuilder ();
  227. string dsColumnName = String.Empty;
  228. bool keyFound = false;
  229. int parmIndex = 1;
  230. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  231. if ((bool)schemaRow["IsExpression"] == true)
  232. continue;
  233. if (!IncludedInWhereClause (schemaRow))
  234. continue;
  235. if (whereClause.Length > 0)
  236. whereClause.Append (" AND ");
  237. bool isKey = (bool) schemaRow ["IsKey"];
  238. SqlParameter parameter = null;
  239. if (isKey)
  240. keyFound = true;
  241. //ms.net 1.1 generates the null check for columns even if AllowDBNull is false
  242. //while ms.net 2.0 does not. Anyways, since both forms are logically equivalent
  243. //following the 2.0 approach
  244. bool allowNull = (bool) schemaRow ["AllowDBNull"];
  245. if (!isKey && allowNull) {
  246. if (option) {
  247. parameter = deleteCommand.Parameters.Add (String.Format ("@{0}",
  248. schemaRow ["BaseColumnName"]),
  249. SqlDbType.Int);
  250. } else {
  251. parameter = deleteCommand.Parameters.Add (String.Format ("@p{0}", parmIndex++),
  252. SqlDbType.Int);
  253. }
  254. String sourceColumnName = (string) schemaRow ["BaseColumnName"];
  255. parameter.Value = 1;
  256. whereClause.Append ("(");
  257. whereClause.Append (String.Format (clause1, parameter.ParameterName,
  258. GetQuotedString (sourceColumnName)));
  259. whereClause.Append (" OR ");
  260. }
  261. if (option) {
  262. parameter = deleteCommand.Parameters.Add (CreateParameter (schemaRow));
  263. } else {
  264. parameter = deleteCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  265. }
  266. parameter.SourceVersion = DataRowVersion.Original;
  267. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  268. if (!isKey && allowNull)
  269. whereClause.Append (")");
  270. }
  271. if (!keyFound)
  272. throw new InvalidOperationException ("Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information.");
  273. // We're all done, so bring it on home
  274. string sql = String.Format ("{0} WHERE ({1})", command, whereClause.ToString ());
  275. deleteCommand.CommandText = sql;
  276. return deleteCommand;
  277. }
  278. private SqlCommand CreateInsertCommand (bool option)
  279. {
  280. if (QuotedTableName == String.Empty)
  281. return null;
  282. CreateNewCommand (ref insertCommand);
  283. string command = String.Format ("INSERT INTO {0}", QuotedTableName);
  284. string sql;
  285. StringBuilder columns = new StringBuilder ();
  286. StringBuilder values = new StringBuilder ();
  287. string dsColumnName = String.Empty;
  288. int parmIndex = 1;
  289. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  290. if (!IncludedInInsert (schemaRow))
  291. continue;
  292. if (parmIndex > 1) {
  293. columns.Append (", ");
  294. values.Append (", ");
  295. }
  296. SqlParameter parameter = null;
  297. if (option) {
  298. parameter = insertCommand.Parameters.Add (CreateParameter (schemaRow));
  299. } else {
  300. parameter = insertCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  301. }
  302. parameter.SourceVersion = DataRowVersion.Current;
  303. columns.Append (GetQuotedString (parameter.SourceColumn));
  304. values.Append (parameter.ParameterName);
  305. }
  306. sql = String.Format ("{0} ({1}) VALUES ({2})", command, columns.ToString (), values.ToString ());
  307. insertCommand.CommandText = sql;
  308. return insertCommand;
  309. }
  310. private void CreateNewCommand (ref SqlCommand command)
  311. {
  312. SqlCommand sourceCommand = SourceCommand;
  313. if (command == null) {
  314. command = sourceCommand.Connection.CreateCommand ();
  315. command.CommandTimeout = sourceCommand.CommandTimeout;
  316. command.Transaction = sourceCommand.Transaction;
  317. }
  318. command.CommandType = CommandType.Text;
  319. command.UpdatedRowSource = UpdateRowSource.None;
  320. command.Parameters.Clear ();
  321. }
  322. private SqlCommand CreateUpdateCommand (bool option)
  323. {
  324. // If no table was found, then we can't do an update
  325. if (QuotedTableName == String.Empty)
  326. return null;
  327. CreateNewCommand (ref updateCommand);
  328. string command = String.Format ("UPDATE {0} SET ", QuotedTableName);
  329. StringBuilder columns = new StringBuilder ();
  330. StringBuilder whereClause = new StringBuilder ();
  331. int parmIndex = 1;
  332. string dsColumnName = String.Empty;
  333. bool keyFound = false;
  334. // First, create the X=Y list for UPDATE
  335. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  336. if (!IncludedInUpdate (schemaRow))
  337. continue;
  338. if (columns.Length > 0)
  339. columns.Append (", ");
  340. SqlParameter parameter = null;
  341. if (option) {
  342. parameter = updateCommand.Parameters.Add (CreateParameter (schemaRow));
  343. } else {
  344. parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  345. }
  346. parameter.SourceVersion = DataRowVersion.Current;
  347. columns.Append (String.Format ("{0} = {1}", GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  348. }
  349. // Now, create the WHERE clause. This may be optimizable, but it would be ugly to incorporate
  350. // into the loop above. "Premature optimization is the root of all evil." -- Knuth
  351. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  352. if ((bool)schemaRow["IsExpression"] == true)
  353. continue;
  354. if (!IncludedInWhereClause (schemaRow))
  355. continue;
  356. if (whereClause.Length > 0)
  357. whereClause.Append (" AND ");
  358. bool isKey = (bool) schemaRow ["IsKey"];
  359. SqlParameter parameter = null;
  360. if (isKey)
  361. keyFound = true;
  362. //ms.net 1.1 generates the null check for columns even if AllowDBNull is false
  363. //while ms.net 2.0 does not. Anyways, since both forms are logically equivalent
  364. //following the 2.0 approach
  365. bool allowNull = (bool) schemaRow ["AllowDBNull"];
  366. if (!isKey && allowNull) {
  367. if (option) {
  368. parameter = updateCommand.Parameters.Add (String.Format ("@{0}",
  369. schemaRow ["BaseColumnName"]),
  370. SqlDbType.Int);
  371. } else {
  372. parameter = updateCommand.Parameters.Add (String.Format ("@p{0}", parmIndex++),
  373. SqlDbType.Int);
  374. }
  375. parameter.Value = 1;
  376. whereClause.Append ("(");
  377. whereClause.Append (String.Format (clause1, parameter.ParameterName,
  378. GetQuotedString ((string) schemaRow ["BaseColumnName"])));
  379. whereClause.Append (" OR ");
  380. }
  381. if (option) {
  382. parameter = updateCommand.Parameters.Add (CreateParameter (schemaRow));
  383. } else {
  384. parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  385. }
  386. parameter.SourceVersion = DataRowVersion.Original;
  387. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  388. if (!isKey && allowNull)
  389. whereClause.Append (")");
  390. }
  391. if (!keyFound)
  392. throw new InvalidOperationException ("Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.");
  393. // We're all done, so bring it on home
  394. string sql = String.Format ("{0}{1} WHERE ({2})", command, columns.ToString (), whereClause.ToString ());
  395. updateCommand.CommandText = sql;
  396. return updateCommand;
  397. }
  398. private SqlParameter CreateParameter (DataRow schemaRow)
  399. {
  400. string sourceColumn = (string) schemaRow ["BaseColumnName"];
  401. string name = String.Format ("@{0}", sourceColumn);
  402. SqlDbType sqlDbType = (SqlDbType) schemaRow ["ProviderType"];
  403. int size = (int) schemaRow ["ColumnSize"];
  404. return new SqlParameter (name, sqlDbType, size, sourceColumn);
  405. }
  406. private SqlParameter CreateParameter (int parmIndex, DataRow schemaRow)
  407. {
  408. string name = String.Format ("@p{0}", parmIndex);
  409. string sourceColumn = (string) schemaRow ["BaseColumnName"];
  410. SqlDbType sqlDbType = (SqlDbType) schemaRow ["ProviderType"];
  411. int size = (int) schemaRow ["ColumnSize"];
  412. return new SqlParameter (name, sqlDbType, size, sourceColumn);
  413. }
  414. public static void DeriveParameters (SqlCommand command)
  415. {
  416. command.DeriveParameters ();
  417. }
  418. #if NET_2_0
  419. new
  420. #else
  421. protected override
  422. #endif
  423. void Dispose (bool disposing)
  424. {
  425. if (!disposed) {
  426. if (disposing) {
  427. if (insertCommand != null)
  428. insertCommand.Dispose ();
  429. if (deleteCommand != null)
  430. deleteCommand.Dispose ();
  431. if (updateCommand != null)
  432. updateCommand.Dispose ();
  433. if (dbSchemaTable != null)
  434. dbSchemaTable.Dispose ();
  435. }
  436. disposed = true;
  437. }
  438. }
  439. public
  440. #if NET_2_0
  441. new
  442. #endif // NET_2_0
  443. SqlCommand GetDeleteCommand ()
  444. {
  445. BuildCache (true);
  446. if (deleteCommand == null)
  447. return CreateDeleteCommand (false);
  448. return deleteCommand;
  449. }
  450. public
  451. #if NET_2_0
  452. new
  453. #endif // NET_2_0
  454. SqlCommand GetInsertCommand ()
  455. {
  456. BuildCache (true);
  457. if (insertCommand == null)
  458. return CreateInsertCommand (false);
  459. return insertCommand;
  460. }
  461. private string GetQuotedString (string value)
  462. {
  463. if (value == String.Empty || value == null)
  464. return value;
  465. if (quotePrefix == String.Empty && quoteSuffix == String.Empty)
  466. return value;
  467. return String.Format ("{0}{1}{2}", quotePrefix, value, quoteSuffix);
  468. }
  469. public
  470. #if NET_2_0
  471. new
  472. #endif // NET_2_0
  473. SqlCommand GetUpdateCommand ()
  474. {
  475. BuildCache (true);
  476. if (updateCommand == null)
  477. return CreateUpdateCommand (false);
  478. return updateCommand;
  479. }
  480. #if NET_2_0
  481. public new SqlCommand GetUpdateCommand (bool option)
  482. {
  483. BuildCache (true);
  484. if (updateCommand == null)
  485. return CreateUpdateCommand (option);
  486. return updateCommand;
  487. }
  488. public new SqlCommand GetDeleteCommand (bool option)
  489. {
  490. BuildCache (true);
  491. if (deleteCommand == null)
  492. return CreateDeleteCommand (option);
  493. return deleteCommand;
  494. }
  495. public new SqlCommand GetInsertCommand (bool option)
  496. {
  497. BuildCache (true);
  498. if (insertCommand == null)
  499. return CreateInsertCommand (option);
  500. return insertCommand;
  501. }
  502. public override string QuoteIdentifier (string unquotedIdentifier)
  503. {
  504. return base.QuoteIdentifier (unquotedIdentifier);
  505. }
  506. public override string UnquoteIdentifier (string quotedIdentifier)
  507. {
  508. return base.UnquoteIdentifier (quotedIdentifier);
  509. }
  510. #endif // NET_2_0
  511. private bool IncludedInInsert (DataRow schemaRow)
  512. {
  513. // If the parameter has one of these properties, then we don't include it in the insert:
  514. // AutoIncrement, Hidden, Expression, RowVersion, ReadOnly
  515. if (!schemaRow.IsNull ("IsAutoIncrement") && (bool) schemaRow ["IsAutoIncrement"])
  516. return false;
  517. if (!schemaRow.IsNull ("IsHidden") && (bool) schemaRow ["IsHidden"])
  518. return false;
  519. if (!schemaRow.IsNull ("IsExpression") && (bool) schemaRow ["IsExpression"])
  520. return false;
  521. if (!schemaRow.IsNull ("IsRowVersion") && (bool) schemaRow ["IsRowVersion"])
  522. return false;
  523. if (!schemaRow.IsNull ("IsReadOnly") && (bool) schemaRow ["IsReadOnly"])
  524. return false;
  525. return true;
  526. }
  527. private bool IncludedInUpdate (DataRow schemaRow)
  528. {
  529. // If the parameter has one of these properties, then we don't include it in the insert:
  530. // AutoIncrement, Hidden, RowVersion
  531. if (!schemaRow.IsNull ("IsAutoIncrement") && (bool) schemaRow ["IsAutoIncrement"])
  532. return false;
  533. if (!schemaRow.IsNull ("IsHidden") && (bool) schemaRow ["IsHidden"])
  534. return false;
  535. if (!schemaRow.IsNull ("IsRowVersion") && (bool) schemaRow ["IsRowVersion"])
  536. return false;
  537. if (!schemaRow.IsNull ("IsExpression") && (bool) schemaRow ["IsExpression"])
  538. return false;
  539. if (!schemaRow.IsNull ("IsReadOnly") && (bool) schemaRow ["IsReadOnly"])
  540. return false;
  541. return true;
  542. }
  543. private bool IncludedInWhereClause (DataRow schemaRow)
  544. {
  545. if ((bool) schemaRow ["IsLong"])
  546. return false;
  547. return true;
  548. }
  549. #if NET_2_0
  550. new
  551. #else
  552. public
  553. #endif
  554. void RefreshSchema ()
  555. {
  556. // FIXME: "Figure out what else needs to be cleaned up when we refresh."
  557. tableName = String.Empty;
  558. dbSchemaTable = null;
  559. CreateNewCommand (ref deleteCommand);
  560. CreateNewCommand (ref updateCommand);
  561. CreateNewCommand (ref insertCommand);
  562. }
  563. #if NET_2_0
  564. protected override void ApplyParameterInfo (DbParameter dbParameter,
  565. DataRow row,
  566. StatementType statementType,
  567. bool whereClause)
  568. {
  569. SqlParameter parameter = (SqlParameter) dbParameter;
  570. parameter.Size = int.Parse (row ["ColumnSize"].ToString ());
  571. if (row ["NumericPrecision"] != DBNull.Value) {
  572. parameter.Precision = byte.Parse (row ["NumericPrecision"].ToString ());
  573. }
  574. if (row ["NumericScale"] != DBNull.Value) {
  575. parameter.Scale = byte.Parse (row ["NumericScale"].ToString ());
  576. }
  577. parameter.SqlDbType = (SqlDbType) row ["ProviderType"];
  578. }
  579. protected override string GetParameterName (int position)
  580. {
  581. return String.Format("@p{0}", position);
  582. }
  583. protected override string GetParameterName (string parameterName)
  584. {
  585. return String.Format("@{0}", parameterName);
  586. }
  587. protected override string GetParameterPlaceholder (int position)
  588. {
  589. return GetParameterName (position);
  590. }
  591. #endif // NET_2_0
  592. #endregion // Methods
  593. #region Event Handlers
  594. private void RowUpdatingHandler (object sender, SqlRowUpdatingEventArgs args)
  595. {
  596. if (args.Command != null)
  597. return;
  598. try {
  599. switch (args.StatementType) {
  600. case StatementType.Insert:
  601. args.Command = GetInsertCommand ();
  602. break;
  603. case StatementType.Update:
  604. args.Command = GetUpdateCommand ();
  605. break;
  606. case StatementType.Delete:
  607. args.Command = GetDeleteCommand ();
  608. break;
  609. }
  610. } catch (Exception e) {
  611. args.Errors = e;
  612. args.Status = UpdateStatus.ErrorsOccurred;
  613. }
  614. }
  615. #if NET_2_0
  616. protected override void SetRowUpdatingHandler (DbDataAdapter adapter)
  617. {
  618. if (!(adapter is SqlDataAdapter)) {
  619. throw new InvalidOperationException ("Adapter needs to be a SqlDataAdapter");
  620. }
  621. rowUpdatingHandler = new SqlRowUpdatingEventHandler (RowUpdatingHandler);
  622. ((SqlDataAdapter) adapter).RowUpdating += rowUpdatingHandler;
  623. }
  624. protected override DataTable GetSchemaTable (DbCommand cmd)
  625. {
  626. using (SqlDataReader rdr = (SqlDataReader) cmd.ExecuteReader ())
  627. return rdr.GetSchemaTable ();
  628. }
  629. protected override DbCommand InitializeCommand (DbCommand cmd)
  630. {
  631. if (cmd == null) {
  632. cmd = new SqlCommand ();
  633. } else {
  634. cmd.CommandTimeout = 30;
  635. cmd.Transaction = null;
  636. cmd.CommandType = CommandType.Text;
  637. cmd.UpdatedRowSource = UpdateRowSource.None;
  638. }
  639. return cmd;
  640. }
  641. #endif // NET_2_0
  642. #endregion // Event Handlers
  643. }
  644. }