SqlCommandBuilder.cs 25 KB

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