OdbcCommandBuilder.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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 NET_1_0
  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 NET_1_0
  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 NET_1_0
  167. protected
  168. #endif
  169. new void Dispose (bool disposing)
  170. {
  171. if (_disposed)
  172. return;
  173. if (disposing) {
  174. // dispose managed resource
  175. if (_insertCommand != null) _insertCommand.Dispose ();
  176. if (_updateCommand != null) _updateCommand.Dispose ();
  177. if (_deleteCommand != null) _deleteCommand.Dispose ();
  178. if (_schema != null) _insertCommand.Dispose ();
  179. _insertCommand = null;
  180. _updateCommand = null;
  181. _deleteCommand = null;
  182. _schema = null;
  183. }
  184. _disposed = true;
  185. }
  186. private bool IsUpdatable (DataRow schemaRow)
  187. {
  188. if ( (! schemaRow.IsNull ("IsAutoIncrement") && (bool) schemaRow ["IsAutoIncrement"])
  189. || (! schemaRow.IsNull ("IsHidden") && (bool) schemaRow ["IsHidden"])
  190. || (! schemaRow.IsNull ("IsExpression") && (bool) schemaRow ["IsExpression"])
  191. || (! schemaRow.IsNull ("IsRowVersion") && (bool) schemaRow ["IsRowVersion"])
  192. || (! schemaRow.IsNull ("IsReadOnly") && (bool) schemaRow ["IsReadOnly"])
  193. )
  194. return false;
  195. return true;
  196. }
  197. private string GetColumnName (DataRow schemaRow)
  198. {
  199. string columnName = schemaRow.IsNull ("BaseColumnName") ? String.Empty : (string) schemaRow ["BaseColumnName"];
  200. if (columnName == String.Empty)
  201. columnName = schemaRow.IsNull ("ColumnName") ? String.Empty : (string) schemaRow ["ColumnName"];
  202. return columnName;
  203. }
  204. private OdbcParameter AddParameter (OdbcCommand cmd, string paramName, OdbcType odbcType,
  205. int length, string sourceColumnName, DataRowVersion rowVersion)
  206. {
  207. OdbcParameter param;
  208. if (length >= 0 && sourceColumnName != String.Empty)
  209. param = cmd.Parameters.Add (paramName, odbcType, length, sourceColumnName);
  210. else
  211. param = cmd.Parameters.Add (paramName, odbcType);
  212. param.SourceVersion = rowVersion;
  213. return param;
  214. }
  215. /*
  216. * creates where clause for optimistic concurrency
  217. */
  218. private string CreateOptWhereClause (OdbcCommand command)
  219. {
  220. string [] whereClause = new string [Schema.Rows.Count];
  221. int count = 0;
  222. foreach (DataRow schemaRow in Schema.Rows) {
  223. // exclude non updatable columns
  224. if (! IsUpdatable (schemaRow))
  225. continue;
  226. string columnName = GetColumnName (schemaRow);
  227. if (columnName == String.Empty)
  228. throw new InvalidOperationException ("Cannot form delete command. Column name is missing!");
  229. bool allowNull = schemaRow.IsNull ("AllowDBNull") || (bool) schemaRow ["AllowDBNull"];
  230. OdbcType sqlDbType = schemaRow.IsNull ("ProviderType") ? OdbcType.VarChar : (OdbcType) schemaRow ["ProviderType"];
  231. int length = schemaRow.IsNull ("ColumnSize") ? -1 : (int) schemaRow ["ColumnSize"];
  232. if (allowNull) {
  233. whereClause [count] = String.Format ("((? = 1 AND {0} IS NULL) OR ({0} = ?))",
  234. columnName);
  235. AddParameter (command, columnName, sqlDbType, length, columnName, DataRowVersion.Original);
  236. AddParameter (command, columnName, sqlDbType, length, columnName, DataRowVersion.Original);
  237. } else {
  238. whereClause [count] = String.Format ( "({0} = ?)", columnName);
  239. AddParameter (command, columnName, sqlDbType, length, columnName, DataRowVersion.Original);
  240. }
  241. count++;
  242. }
  243. return String.Join (" AND ", whereClause, 0, count);
  244. }
  245. public
  246. #if NET_2_0
  247. new
  248. #endif // NET_2_0
  249. OdbcCommand GetInsertCommand ()
  250. {
  251. // FIXME: check validity of adapter
  252. if (_insertCommand != null)
  253. return _insertCommand;
  254. if (_schema == null)
  255. RefreshSchema ();
  256. _insertCommand = new OdbcCommand ();
  257. _insertCommand.Connection = DataAdapter.SelectCommand.Connection;
  258. _insertCommand.Transaction = DataAdapter.SelectCommand.Transaction;
  259. _insertCommand.CommandType = CommandType.Text;
  260. _insertCommand.UpdatedRowSource = UpdateRowSource.None;
  261. string query = String.Format ("INSERT INTO {0}", QuoteIdentifier (TableName));
  262. string [] columns = new string [Schema.Rows.Count];
  263. string [] values = new string [Schema.Rows.Count];
  264. int count = 0;
  265. foreach (DataRow schemaRow in Schema.Rows) {
  266. // exclude non updatable columns
  267. if (! IsUpdatable (schemaRow))
  268. continue;
  269. string columnName = GetColumnName (schemaRow);
  270. if (columnName == String.Empty)
  271. throw new InvalidOperationException ("Cannot form insert command. Column name is missing!");
  272. // create column string & value string
  273. columns [count] = QuoteIdentifier(columnName);
  274. values [count++] = "?";
  275. // create parameter and add
  276. OdbcType sqlDbType = schemaRow.IsNull ("ProviderType") ? OdbcType.VarChar : (OdbcType) schemaRow ["ProviderType"];
  277. int length = schemaRow.IsNull ("ColumnSize") ? -1 : (int) schemaRow ["ColumnSize"];
  278. AddParameter (_insertCommand, columnName, sqlDbType, length, columnName, DataRowVersion.Current);
  279. }
  280. query = String.Format ("{0} ({1}) VALUES ({2})",
  281. query,
  282. String.Join (", ", columns, 0, count),
  283. String.Join (", ", values, 0, count) );
  284. _insertCommand.CommandText = query;
  285. return _insertCommand;
  286. }
  287. #if NET_2_0
  288. [MonoTODO]
  289. public new OdbcCommand GetInsertCommand (bool option)
  290. {
  291. // FIXME: check validity of adapter
  292. if (_insertCommand != null)
  293. return _insertCommand;
  294. if (_schema == null)
  295. RefreshSchema ();
  296. if (option == false) {
  297. return GetInsertCommand ();
  298. } else {
  299. throw new NotImplementedException ();
  300. }
  301. }
  302. #endif // NET_2_0
  303. public
  304. #if NET_2_0
  305. new
  306. #endif // NET_2_0
  307. OdbcCommand GetUpdateCommand ()
  308. {
  309. // FIXME: check validity of adapter
  310. if (_updateCommand != null)
  311. return _updateCommand;
  312. if (_schema == null)
  313. RefreshSchema ();
  314. _updateCommand = new OdbcCommand ();
  315. _updateCommand.Connection = DataAdapter.SelectCommand.Connection;
  316. _updateCommand.Transaction = DataAdapter.SelectCommand.Transaction;
  317. _updateCommand.CommandType = CommandType.Text;
  318. _updateCommand.UpdatedRowSource = UpdateRowSource.None;
  319. string query = String.Format ("UPDATE {0} SET", QuoteIdentifier (TableName));
  320. string [] setClause = new string [Schema.Rows.Count];
  321. int count = 0;
  322. foreach (DataRow schemaRow in Schema.Rows) {
  323. // exclude non updatable columns
  324. if (! IsUpdatable (schemaRow))
  325. continue;
  326. string columnName = GetColumnName (schemaRow);
  327. if (columnName == String.Empty)
  328. throw new InvalidOperationException ("Cannot form update command. Column name is missing!");
  329. OdbcType sqlDbType = schemaRow.IsNull ("ProviderType") ? OdbcType.VarChar : (OdbcType) schemaRow ["ProviderType"];
  330. int length = schemaRow.IsNull ("ColumnSize") ? -1 : (int) schemaRow ["ColumnSize"];
  331. // create column = value string
  332. setClause [count] = String.Format ("{0} = ?", QuoteIdentifier(columnName));
  333. AddParameter (_updateCommand, columnName, sqlDbType, length, columnName, DataRowVersion.Current);
  334. count++;
  335. }
  336. // create where clause. odbc uses positional parameters. so where class
  337. // is created seperate from the above loop.
  338. string whereClause = CreateOptWhereClause (_updateCommand);
  339. query = String.Format ("{0} {1} WHERE ({2})",
  340. query,
  341. String.Join (", ", setClause, 0, count),
  342. whereClause);
  343. _updateCommand.CommandText = query;
  344. return _updateCommand;
  345. }
  346. #if NET_2_0
  347. [MonoTODO]
  348. public new OdbcCommand GetUpdateCommand (bool option)
  349. {
  350. // FIXME: check validity of adapter
  351. if (_updateCommand != null)
  352. return _updateCommand;
  353. if (_schema == null)
  354. RefreshSchema ();
  355. if (option == false) {
  356. return GetUpdateCommand ();
  357. } else {
  358. throw new NotImplementedException ();
  359. }
  360. }
  361. #endif // NET_2_0
  362. public
  363. #if NET_2_0
  364. new
  365. #endif // NET_2_0
  366. OdbcCommand GetDeleteCommand ()
  367. {
  368. // FIXME: check validity of adapter
  369. if (_deleteCommand != null)
  370. return _deleteCommand;
  371. if (_schema == null)
  372. RefreshSchema ();
  373. _deleteCommand = new OdbcCommand ();
  374. _deleteCommand.Connection = DataAdapter.SelectCommand.Connection;
  375. _deleteCommand.Transaction = DataAdapter.SelectCommand.Transaction;
  376. _deleteCommand.CommandType = CommandType.Text;
  377. _deleteCommand.UpdatedRowSource = UpdateRowSource.None;
  378. string query = String.Format ("DELETE FROM {0}", QuoteIdentifier (TableName));
  379. string whereClause = CreateOptWhereClause (_deleteCommand);
  380. query = String.Format ("{0} WHERE ({1})", query, whereClause);
  381. _deleteCommand.CommandText = query;
  382. return _deleteCommand;
  383. }
  384. #if NET_2_0
  385. [MonoTODO]
  386. public new OdbcCommand GetDeleteCommand (bool option)
  387. {
  388. // FIXME: check validity of adapter
  389. if (_deleteCommand != null)
  390. return _deleteCommand;
  391. if (_schema == null)
  392. RefreshSchema ();
  393. if (option == false) {
  394. return GetDeleteCommand ();
  395. } else {
  396. throw new NotImplementedException ();
  397. }
  398. }
  399. #endif // NET_2_0
  400. #if NET_1_0
  401. public
  402. #else
  403. new
  404. #endif // NET_2_0
  405. void RefreshSchema ()
  406. {
  407. // creates metadata
  408. if (SelectCommand == null)
  409. throw new InvalidOperationException ("SelectCommand should be valid");
  410. if (SelectCommand.Connection == null)
  411. throw new InvalidOperationException ("SelectCommand's Connection should be valid");
  412. CommandBehavior behavior = CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  413. if (SelectCommand.Connection.State != ConnectionState.Open) {
  414. SelectCommand.Connection.Open ();
  415. behavior |= CommandBehavior.CloseConnection;
  416. }
  417. OdbcDataReader reader = SelectCommand.ExecuteReader (behavior);
  418. _schema = reader.GetSchemaTable ();
  419. reader.Close ();
  420. // force creation of commands
  421. _insertCommand = null;
  422. _updateCommand = null;
  423. _deleteCommand = null;
  424. _tableName = String.Empty;
  425. }
  426. #if NET_2_0
  427. protected override void ApplyParameterInfo (DbParameter dbParameter,
  428. DataRow row,
  429. StatementType statementType,
  430. bool whereClause)
  431. {
  432. OdbcParameter parameter = (OdbcParameter) dbParameter;
  433. parameter.Size = int.Parse (row ["ColumnSize"].ToString ());
  434. if (row ["NumericPrecision"] != DBNull.Value) {
  435. parameter.Precision = byte.Parse (row ["NumericPrecision"].ToString ());
  436. }
  437. if (row ["NumericScale"] != DBNull.Value) {
  438. parameter.Scale = byte.Parse (row ["NumericScale"].ToString ());
  439. }
  440. parameter.DbType = (DbType) row ["ProviderType"];
  441. }
  442. protected override string GetParameterName (int position)
  443. {
  444. return String.Format("@p{0}", position);
  445. }
  446. protected override string GetParameterName (string parameterName)
  447. {
  448. return String.Format("@{0}", parameterName);
  449. }
  450. protected override string GetParameterPlaceholder (int position)
  451. {
  452. return GetParameterName (position);
  453. }
  454. [MonoTODO]
  455. protected override void SetRowUpdatingHandler (DbDataAdapter adapter)
  456. {
  457. throw new NotImplementedException ();
  458. }
  459. #endif // NET_2_0
  460. #if NET_2_0
  461. public override
  462. #else
  463. private
  464. #endif
  465. string QuoteIdentifier (string unquotedIdentifier)
  466. {
  467. if (unquotedIdentifier == null || unquotedIdentifier == String.Empty)
  468. return unquotedIdentifier;
  469. return String.Format ("{0}{1}{2}", QuotePrefix,
  470. unquotedIdentifier, QuoteSuffix);
  471. }
  472. #if NET_2_0
  473. [MonoTODO]
  474. public string QuoteIdentifier (string unquotedIdentifier, OdbcConnection connection)
  475. {
  476. throw new NotImplementedException ();
  477. }
  478. [MonoTODO]
  479. public string UnquoteIdentifier (string unquotedIdentifier, OdbcConnection connection)
  480. {
  481. throw new NotImplementedException ();
  482. }
  483. #endif
  484. #if NET_2_0
  485. public override
  486. #else
  487. private
  488. #endif
  489. string UnquoteIdentifier (string quotedIdentifier)
  490. {
  491. if (quotedIdentifier == null || quotedIdentifier == String.Empty)
  492. return quotedIdentifier;
  493. StringBuilder sb = new StringBuilder (quotedIdentifier.Length);
  494. sb.Append (quotedIdentifier);
  495. if (quotedIdentifier.StartsWith (QuotePrefix))
  496. sb.Remove (0,QuotePrefix.Length);
  497. if (quotedIdentifier.EndsWith (QuoteSuffix))
  498. sb.Remove (sb.Length - QuoteSuffix.Length, QuoteSuffix.Length );
  499. return sb.ToString ();
  500. }
  501. private void OnRowUpdating (object sender, OdbcRowUpdatingEventArgs args)
  502. {
  503. if (args.Command != null)
  504. return;
  505. try {
  506. switch (args.StatementType) {
  507. case StatementType.Insert:
  508. args.Command = GetInsertCommand ();
  509. break;
  510. case StatementType.Update:
  511. args.Command = GetUpdateCommand ();
  512. break;
  513. case StatementType.Delete:
  514. args.Command = GetDeleteCommand ();
  515. break;
  516. }
  517. } catch (Exception e) {
  518. args.Errors = e;
  519. args.Status = UpdateStatus.ErrorsOccurred;
  520. }
  521. }
  522. #endregion // Methods
  523. }
  524. }