OdbcCommandBuilder.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. //
  2. // System.Data.Odbc.OdbcCommandBuilder
  3. //
  4. // Author:
  5. // Umadevi S ([email protected])
  6. // Sureshkumar T ([email protected])
  7. //
  8. // Copyright (C) Novell Inc, 2004
  9. //
  10. //
  11. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System.Text;
  33. using System.Data;
  34. using System.Data.Common;
  35. using System.ComponentModel;
  36. namespace System.Data.Odbc
  37. {
  38. /// <summary>
  39. /// Provides a means of automatically generating single-table commands used to reconcile changes made to a DataSet with the associated database. This class cannot be inherited.
  40. /// </summary>
  41. #if NET_2_0
  42. public sealed class OdbcCommandBuilder : DbCommandBuilder
  43. #else // 1_1
  44. public sealed class OdbcCommandBuilder : Component
  45. #endif // NET_2_0
  46. {
  47. #region Fields
  48. private OdbcDataAdapter _adapter;
  49. private string _quotePrefix;
  50. private string _quoteSuffix;
  51. private DataTable _schema;
  52. private string _tableName;
  53. private OdbcCommand _insertCommand;
  54. private OdbcCommand _updateCommand;
  55. private OdbcCommand _deleteCommand;
  56. bool _disposed;
  57. #endregion // Fields
  58. #region Constructors
  59. public OdbcCommandBuilder ()
  60. {
  61. _adapter = null;
  62. _quotePrefix = String.Empty;
  63. _quoteSuffix = String.Empty;
  64. }
  65. public OdbcCommandBuilder (OdbcDataAdapter adapter)
  66. : this ()
  67. {
  68. DataAdapter = adapter;
  69. }
  70. #endregion // Constructors
  71. #region Properties
  72. [OdbcDescriptionAttribute ("The DataAdapter for which to automatically generate OdbcCommands")]
  73. [DefaultValue (null)]
  74. public
  75. #if NET_2_0
  76. new
  77. #endif // NET_2_0
  78. OdbcDataAdapter DataAdapter {
  79. get {
  80. return _adapter;
  81. }
  82. set {
  83. if (_adapter == value)
  84. return;
  85. if (_adapter != null)
  86. _adapter.RowUpdating -= new OdbcRowUpdatingEventHandler (OnRowUpdating);
  87. _adapter = value;
  88. if (_adapter != null)
  89. _adapter.RowUpdating += new OdbcRowUpdatingEventHandler (OnRowUpdating);
  90. }
  91. }
  92. private OdbcCommand SelectCommand
  93. {
  94. get {
  95. if (DataAdapter == null)
  96. return null;
  97. return DataAdapter.SelectCommand;
  98. }
  99. }
  100. private DataTable Schema
  101. {
  102. get {
  103. if (_schema == null)
  104. RefreshSchema ();
  105. return _schema;
  106. }
  107. }
  108. private string TableName
  109. {
  110. get {
  111. if (_tableName != String.Empty)
  112. return _tableName;
  113. DataRow [] schemaRows = Schema.Select ("BaseTableName is not null and BaseTableName <> ''");
  114. if (schemaRows.Length > 1) {
  115. string tableName = (string) schemaRows [0] ["BaseTableName"];
  116. foreach (DataRow schemaRow in schemaRows) {
  117. if ( (string) schemaRow ["BaseTableName"] != tableName)
  118. throw new InvalidOperationException ("Dynamic SQL generation is not supported against multiple base tables.");
  119. }
  120. }
  121. if (schemaRows.Length == 0)
  122. throw new InvalidOperationException ("Cannot determine the base table name. Cannot proceed");
  123. _tableName = schemaRows [0] ["BaseTableName"].ToString ();
  124. return _tableName;
  125. }
  126. }
  127. [BrowsableAttribute (false)]
  128. [OdbcDescriptionAttribute ("The prefix string wrapped around sql objects")]
  129. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  130. #if ONLY_1_1
  131. public
  132. #else
  133. new
  134. #endif
  135. string QuotePrefix {
  136. get {
  137. return _quotePrefix;
  138. }
  139. set {
  140. _quotePrefix = value;
  141. }
  142. }
  143. [BrowsableAttribute (false)]
  144. [OdbcDescriptionAttribute ("The suffix string wrapped around sql objects")]
  145. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  146. #if ONLY_1_1
  147. public
  148. #else
  149. new
  150. #endif // NET_2_0
  151. string QuoteSuffix {
  152. get {
  153. return _quoteSuffix;
  154. }
  155. set {
  156. _quoteSuffix = value;
  157. }
  158. }
  159. #endregion // Properties
  160. #region Methods
  161. [MonoTODO]
  162. public static void DeriveParameters (OdbcCommand command)
  163. {
  164. throw new NotImplementedException ();
  165. }
  166. #if ONLY_1_1
  167. protected override
  168. #else
  169. new
  170. #endif
  171. void Dispose (bool disposing)
  172. {
  173. if (_disposed)
  174. return;
  175. if (disposing) {
  176. // dispose managed resource
  177. if (_insertCommand != null) _insertCommand.Dispose ();
  178. if (_updateCommand != null) _updateCommand.Dispose ();
  179. if (_deleteCommand != null) _deleteCommand.Dispose ();
  180. if (_schema != null) _insertCommand.Dispose ();
  181. _insertCommand = null;
  182. _updateCommand = null;
  183. _deleteCommand = null;
  184. _schema = null;
  185. }
  186. _disposed = true;
  187. }
  188. private bool IsUpdatable (DataRow schemaRow)
  189. {
  190. if ( (! schemaRow.IsNull ("IsAutoIncrement") && (bool) schemaRow ["IsAutoIncrement"])
  191. || (! schemaRow.IsNull ("IsHidden") && (bool) schemaRow ["IsHidden"])
  192. || (! schemaRow.IsNull ("IsExpression") && (bool) schemaRow ["IsExpression"])
  193. || (! schemaRow.IsNull ("IsRowVersion") && (bool) schemaRow ["IsRowVersion"])
  194. || (! schemaRow.IsNull ("IsReadOnly") && (bool) schemaRow ["IsReadOnly"])
  195. )
  196. return false;
  197. return true;
  198. }
  199. private string GetColumnName (DataRow schemaRow)
  200. {
  201. string columnName = schemaRow.IsNull ("BaseColumnName") ? String.Empty : (string) schemaRow ["BaseColumnName"];
  202. if (columnName == String.Empty)
  203. columnName = schemaRow.IsNull ("ColumnName") ? String.Empty : (string) schemaRow ["ColumnName"];
  204. return columnName;
  205. }
  206. private OdbcParameter AddParameter (OdbcCommand cmd, string paramName, OdbcType odbcType,
  207. int length, string sourceColumnName, DataRowVersion rowVersion)
  208. {
  209. OdbcParameter param;
  210. if (length >= 0 && sourceColumnName != String.Empty)
  211. param = cmd.Parameters.Add (paramName, odbcType, length, sourceColumnName);
  212. else
  213. param = cmd.Parameters.Add (paramName, odbcType);
  214. param.SourceVersion = rowVersion;
  215. return param;
  216. }
  217. /*
  218. * creates where clause for optimistic concurrency
  219. */
  220. private string CreateOptWhereClause (OdbcCommand command)
  221. {
  222. string [] whereClause = new string [Schema.Rows.Count];
  223. int count = 0;
  224. foreach (DataRow schemaRow in Schema.Rows) {
  225. // exclude non updatable columns
  226. if (! IsUpdatable (schemaRow))
  227. continue;
  228. string columnName = GetColumnName (schemaRow);
  229. if (columnName == String.Empty)
  230. throw new InvalidOperationException ("Cannot form delete command. Column name is missing!");
  231. bool allowNull = schemaRow.IsNull ("AllowDBNull") || (bool) schemaRow ["AllowDBNull"];
  232. OdbcType sqlDbType = schemaRow.IsNull ("ProviderType") ? OdbcType.VarChar : (OdbcType) schemaRow ["ProviderType"];
  233. int length = schemaRow.IsNull ("ColumnSize") ? -1 : (int) schemaRow ["ColumnSize"];
  234. if (allowNull) {
  235. whereClause [count] = String.Format ("((? = 1 AND {0} IS NULL) OR ({0} = ?))",
  236. columnName);
  237. AddParameter (command, columnName, sqlDbType, length, columnName, DataRowVersion.Original);
  238. AddParameter (command, columnName, sqlDbType, length, columnName, DataRowVersion.Original);
  239. } else {
  240. whereClause [count] = String.Format ( "({0} = ?)", columnName);
  241. AddParameter (command, columnName, sqlDbType, length, columnName, DataRowVersion.Original);
  242. }
  243. count++;
  244. }
  245. return String.Join (" AND ", whereClause, 0, count);
  246. }
  247. public
  248. #if NET_2_0
  249. new
  250. #endif // NET_2_0
  251. OdbcCommand GetInsertCommand ()
  252. {
  253. // FIXME: check validity of adapter
  254. if (_insertCommand != null)
  255. return _insertCommand;
  256. if (_schema == null)
  257. RefreshSchema ();
  258. _insertCommand = new OdbcCommand ();
  259. _insertCommand.Connection = DataAdapter.SelectCommand.Connection;
  260. _insertCommand.Transaction = DataAdapter.SelectCommand.Transaction;
  261. _insertCommand.CommandType = CommandType.Text;
  262. _insertCommand.UpdatedRowSource = UpdateRowSource.None;
  263. string query = String.Format ("INSERT INTO {0}", QuoteIdentifier (TableName));
  264. string [] columns = new string [Schema.Rows.Count];
  265. string [] values = new string [Schema.Rows.Count];
  266. int count = 0;
  267. foreach (DataRow schemaRow in Schema.Rows) {
  268. // exclude non updatable columns
  269. if (! IsUpdatable (schemaRow))
  270. continue;
  271. string columnName = GetColumnName (schemaRow);
  272. if (columnName == String.Empty)
  273. throw new InvalidOperationException ("Cannot form insert command. Column name is missing!");
  274. // create column string & value string
  275. columns [count] = QuoteIdentifier(columnName);
  276. values [count++] = "?";
  277. // create parameter and add
  278. OdbcType sqlDbType = schemaRow.IsNull ("ProviderType") ? OdbcType.VarChar : (OdbcType) schemaRow ["ProviderType"];
  279. int length = schemaRow.IsNull ("ColumnSize") ? -1 : (int) schemaRow ["ColumnSize"];
  280. AddParameter (_insertCommand, columnName, sqlDbType, length, columnName, DataRowVersion.Current);
  281. }
  282. query = String.Format ("{0} ({1}) VALUES ({2})",
  283. query,
  284. String.Join (", ", columns, 0, count),
  285. String.Join (", ", values, 0, count) );
  286. _insertCommand.CommandText = query;
  287. return _insertCommand;
  288. }
  289. #if NET_2_0
  290. [MonoTODO]
  291. public new OdbcCommand GetInsertCommand (bool option)
  292. {
  293. // FIXME: check validity of adapter
  294. if (_insertCommand != null)
  295. return _insertCommand;
  296. if (_schema == null)
  297. RefreshSchema ();
  298. if (option == false) {
  299. return GetInsertCommand ();
  300. } else {
  301. throw new NotImplementedException ();
  302. }
  303. }
  304. #endif // NET_2_0
  305. public
  306. #if NET_2_0
  307. new
  308. #endif // NET_2_0
  309. OdbcCommand GetUpdateCommand ()
  310. {
  311. // FIXME: check validity of adapter
  312. if (_updateCommand != null)
  313. return _updateCommand;
  314. if (_schema == null)
  315. RefreshSchema ();
  316. _updateCommand = new OdbcCommand ();
  317. _updateCommand.Connection = DataAdapter.SelectCommand.Connection;
  318. _updateCommand.Transaction = DataAdapter.SelectCommand.Transaction;
  319. _updateCommand.CommandType = CommandType.Text;
  320. _updateCommand.UpdatedRowSource = UpdateRowSource.None;
  321. string query = String.Format ("UPDATE {0} SET", QuoteIdentifier (TableName));
  322. string [] setClause = new string [Schema.Rows.Count];
  323. int count = 0;
  324. foreach (DataRow schemaRow in Schema.Rows) {
  325. // exclude non updatable columns
  326. if (! IsUpdatable (schemaRow))
  327. continue;
  328. string columnName = GetColumnName (schemaRow);
  329. if (columnName == String.Empty)
  330. throw new InvalidOperationException ("Cannot form update command. Column name is missing!");
  331. OdbcType sqlDbType = schemaRow.IsNull ("ProviderType") ? OdbcType.VarChar : (OdbcType) schemaRow ["ProviderType"];
  332. int length = schemaRow.IsNull ("ColumnSize") ? -1 : (int) schemaRow ["ColumnSize"];
  333. // create column = value string
  334. setClause [count] = String.Format ("{0} = ?", QuoteIdentifier(columnName));
  335. AddParameter (_updateCommand, columnName, sqlDbType, length, columnName, DataRowVersion.Current);
  336. count++;
  337. }
  338. // create where clause. odbc uses positional parameters. so where class
  339. // is created seperate from the above loop.
  340. string whereClause = CreateOptWhereClause (_updateCommand);
  341. query = String.Format ("{0} {1} WHERE ({2})",
  342. query,
  343. String.Join (", ", setClause, 0, count),
  344. whereClause);
  345. _updateCommand.CommandText = query;
  346. return _updateCommand;
  347. }
  348. #if NET_2_0
  349. [MonoTODO]
  350. public new OdbcCommand GetUpdateCommand (bool option)
  351. {
  352. // FIXME: check validity of adapter
  353. if (_updateCommand != null)
  354. return _updateCommand;
  355. if (_schema == null)
  356. RefreshSchema ();
  357. if (option == false) {
  358. return GetUpdateCommand ();
  359. } else {
  360. throw new NotImplementedException ();
  361. }
  362. }
  363. #endif // NET_2_0
  364. public
  365. #if NET_2_0
  366. new
  367. #endif // NET_2_0
  368. OdbcCommand GetDeleteCommand ()
  369. {
  370. // FIXME: check validity of adapter
  371. if (_deleteCommand != null)
  372. return _deleteCommand;
  373. if (_schema == null)
  374. RefreshSchema ();
  375. _deleteCommand = new OdbcCommand ();
  376. _deleteCommand.Connection = DataAdapter.SelectCommand.Connection;
  377. _deleteCommand.Transaction = DataAdapter.SelectCommand.Transaction;
  378. _deleteCommand.CommandType = CommandType.Text;
  379. _deleteCommand.UpdatedRowSource = UpdateRowSource.None;
  380. string query = String.Format ("DELETE FROM {0}", QuoteIdentifier (TableName));
  381. string whereClause = CreateOptWhereClause (_deleteCommand);
  382. query = String.Format ("{0} WHERE ({1})", query, whereClause);
  383. _deleteCommand.CommandText = query;
  384. return _deleteCommand;
  385. }
  386. #if NET_2_0
  387. [MonoTODO]
  388. public new OdbcCommand GetDeleteCommand (bool option)
  389. {
  390. // FIXME: check validity of adapter
  391. if (_deleteCommand != null)
  392. return _deleteCommand;
  393. if (_schema == null)
  394. RefreshSchema ();
  395. if (option == false) {
  396. return GetDeleteCommand ();
  397. } else {
  398. throw new NotImplementedException ();
  399. }
  400. }
  401. #endif // NET_2_0
  402. #if ONLY_1_1
  403. public
  404. #else
  405. new
  406. #endif // NET_2_0
  407. void RefreshSchema ()
  408. {
  409. // creates metadata
  410. if (SelectCommand == null)
  411. throw new InvalidOperationException ("SelectCommand should be valid");
  412. if (SelectCommand.Connection == null)
  413. throw new InvalidOperationException ("SelectCommand's Connection should be valid");
  414. CommandBehavior behavior = CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  415. if (SelectCommand.Connection.State != ConnectionState.Open) {
  416. SelectCommand.Connection.Open ();
  417. behavior |= CommandBehavior.CloseConnection;
  418. }
  419. OdbcDataReader reader = SelectCommand.ExecuteReader (behavior);
  420. _schema = reader.GetSchemaTable ();
  421. reader.Close ();
  422. // force creation of commands
  423. _insertCommand = null;
  424. _updateCommand = null;
  425. _deleteCommand = null;
  426. _tableName = String.Empty;
  427. }
  428. #if NET_2_0
  429. protected override void ApplyParameterInfo (DbParameter dbParameter,
  430. DataRow row,
  431. StatementType statementType,
  432. bool whereClause)
  433. {
  434. OdbcParameter parameter = (OdbcParameter) dbParameter;
  435. parameter.Size = int.Parse (row ["ColumnSize"].ToString ());
  436. if (row ["NumericPrecision"] != DBNull.Value) {
  437. parameter.Precision = byte.Parse (row ["NumericPrecision"].ToString ());
  438. }
  439. if (row ["NumericScale"] != DBNull.Value) {
  440. parameter.Scale = byte.Parse (row ["NumericScale"].ToString ());
  441. }
  442. parameter.DbType = (DbType) row ["ProviderType"];
  443. }
  444. protected override string GetParameterName (int position)
  445. {
  446. return String.Format("@p{0}", position);
  447. }
  448. protected override string GetParameterName (string parameterName)
  449. {
  450. return String.Format("@{0}", parameterName);
  451. }
  452. protected override string GetParameterPlaceholder (int position)
  453. {
  454. return GetParameterName (position);
  455. }
  456. [MonoTODO]
  457. protected override void SetRowUpdatingHandler (DbDataAdapter adapter)
  458. {
  459. throw new NotImplementedException ();
  460. }
  461. #endif // NET_2_0
  462. #if NET_2_0
  463. public override
  464. #else
  465. private
  466. #endif
  467. string QuoteIdentifier (string unquotedIdentifier)
  468. {
  469. if (unquotedIdentifier == null || unquotedIdentifier == String.Empty)
  470. return unquotedIdentifier;
  471. return String.Format ("{0}{1}{2}", QuotePrefix,
  472. unquotedIdentifier, QuoteSuffix);
  473. }
  474. #if NET_2_0
  475. [MonoTODO]
  476. public string QuoteIdentifier (string unquotedIdentifier, OdbcConnection connection)
  477. {
  478. throw new NotImplementedException ();
  479. }
  480. [MonoTODO]
  481. public string UnquoteIdentifier (string unquotedIdentifier, OdbcConnection connection)
  482. {
  483. throw new NotImplementedException ();
  484. }
  485. #endif
  486. #if NET_2_0
  487. public override
  488. #else
  489. private
  490. #endif
  491. string UnquoteIdentifier (string quotedIdentifier)
  492. {
  493. if (quotedIdentifier == null || quotedIdentifier == String.Empty)
  494. return quotedIdentifier;
  495. StringBuilder sb = new StringBuilder (quotedIdentifier.Length);
  496. sb.Append (quotedIdentifier);
  497. if (quotedIdentifier.StartsWith (QuotePrefix))
  498. sb.Remove (0,QuotePrefix.Length);
  499. if (quotedIdentifier.EndsWith (QuoteSuffix))
  500. sb.Remove (sb.Length - QuoteSuffix.Length, QuoteSuffix.Length );
  501. return sb.ToString ();
  502. }
  503. private void OnRowUpdating (object sender, OdbcRowUpdatingEventArgs args)
  504. {
  505. if (args.Command != null)
  506. return;
  507. try {
  508. switch (args.StatementType) {
  509. case StatementType.Insert:
  510. args.Command = GetInsertCommand ();
  511. break;
  512. case StatementType.Update:
  513. args.Command = GetUpdateCommand ();
  514. break;
  515. case StatementType.Delete:
  516. args.Command = GetDeleteCommand ();
  517. break;
  518. }
  519. } catch (Exception e) {
  520. args.Errors = e;
  521. args.Status = UpdateStatus.ErrorsOccurred;
  522. }
  523. }
  524. #endregion // Methods
  525. }
  526. }