SqlBulkCopy.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. //
  2. // System.Data.SqlClient.SqlBulkCopy.cs
  3. //
  4. // Author:
  5. // Nagappan A ([email protected])
  6. //
  7. // (C) Novell, Inc 2007
  8. //
  9. // Copyright (C) 2007 Novell, Inc (http://www.novell.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. #if NET_2_0
  31. using System;
  32. using System.Data;
  33. using System.Data.Common;
  34. using Mono.Data.Tds;
  35. using Mono.Data.Tds.Protocol;
  36. namespace System.Data.SqlClient {
  37. public sealed class SqlBulkCopy : IDisposable
  38. {
  39. #region Fields
  40. private int _batchSize = 0;
  41. private int _notifyAfter = 0;
  42. private int _bulkCopyTimeout = 0;
  43. private SqlBulkCopyColumnMappingCollection _columnMappingCollection = new SqlBulkCopyColumnMappingCollection ();
  44. private string _destinationTableName = null;
  45. private bool ordinalMapping = false;
  46. bool sqlRowsCopied = false;
  47. bool identityInsert = false;
  48. bool isLocalConnection = false;
  49. SqlConnection connection;
  50. SqlBulkCopyOptions copyOptions = SqlBulkCopyOptions.Default;
  51. #endregion
  52. #region Constructors
  53. public SqlBulkCopy (SqlConnection connection)
  54. {
  55. this.connection = connection;
  56. }
  57. public SqlBulkCopy (string connectionString)
  58. {
  59. this.connection = new SqlConnection (connectionString);
  60. isLocalConnection = true;
  61. }
  62. [MonoTODO]
  63. public SqlBulkCopy (string connectionString, SqlBulkCopyOptions copyOptions)
  64. {
  65. this.connection = new SqlConnection (connectionString);
  66. this.copyOptions = copyOptions;
  67. isLocalConnection = true;
  68. throw new NotImplementedException ();
  69. }
  70. [MonoTODO]
  71. public SqlBulkCopy (SqlConnection connection, SqlBulkCopyOptions copyOptions, SqlTransaction externalTransaction)
  72. {
  73. this.connection = connection;
  74. this.copyOptions = copyOptions;
  75. throw new NotImplementedException ();
  76. }
  77. #endregion
  78. #region Properties
  79. public int BatchSize {
  80. get { return _batchSize; }
  81. set { _batchSize = value; }
  82. }
  83. public int BulkCopyTimeout {
  84. get { return _bulkCopyTimeout; }
  85. set { _bulkCopyTimeout = value; }
  86. }
  87. public SqlBulkCopyColumnMappingCollection ColumnMappings {
  88. get { return _columnMappingCollection; }
  89. }
  90. public string DestinationTableName {
  91. get { return _destinationTableName; }
  92. set { _destinationTableName = value; }
  93. }
  94. public int NotifyAfter {
  95. get { return _notifyAfter; }
  96. set {
  97. if (value < 0)
  98. throw new ArgumentOutOfRangeException ("NotifyAfter should be greater than or equal to 0");
  99. _notifyAfter = value;
  100. }
  101. }
  102. #endregion
  103. #region Methods
  104. public void Close ()
  105. {
  106. if (sqlRowsCopied == true) {
  107. throw new InvalidOperationException ("Close should not be called from SqlRowsCopied event");
  108. }
  109. if (connection == null || connection.State == ConnectionState.Closed) {
  110. return;
  111. }
  112. connection.Close ();
  113. }
  114. private DataTable [] GetColumnMetaData ()
  115. {
  116. DataTable [] columnMetaDataTables = new DataTable [2];
  117. SqlCommand cmd = new SqlCommand ("select @@trancount; " +
  118. "set fmtonly on select * from " +
  119. DestinationTableName + " set fmtonly off;" +
  120. "exec sp_tablecollations_90 '" +
  121. DestinationTableName + "'",
  122. connection);
  123. SqlDataReader reader = cmd.ExecuteReader ();
  124. int i = 0; // Skipping 1st result
  125. do {
  126. if (i == 1) {
  127. columnMetaDataTables [i - 1] = reader.GetSchemaTable ();
  128. } else if (i == 2) {
  129. SqlDataAdapter adapter = new SqlDataAdapter ();
  130. adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
  131. columnMetaDataTables [i - 1] = new DataTable ();
  132. adapter.FillInternal (columnMetaDataTables [i - 1], reader);
  133. }
  134. i++;
  135. } while (reader.IsClosed == false && reader.NextResult());
  136. reader.Close ();
  137. return columnMetaDataTables;
  138. }
  139. private string GenerateColumnMetaData (SqlCommand tmpCmd, DataTable colMetaData, DataTable tableCollations)
  140. {
  141. bool flag = false;
  142. string statement = "";
  143. int i = 0;
  144. foreach (DataRow row in colMetaData.Rows) {
  145. flag = false;
  146. foreach (DataColumn col in colMetaData.Columns) { // FIXME: This line not required, remove later
  147. object value = null;
  148. if (_columnMappingCollection.Count > 0) {
  149. if (ordinalMapping) {
  150. foreach (SqlBulkCopyColumnMapping mapping
  151. in _columnMappingCollection) {
  152. if (mapping.DestinationOrdinal == i) {
  153. flag = true;
  154. break;
  155. }
  156. }
  157. } else {
  158. foreach (SqlBulkCopyColumnMapping mapping
  159. in _columnMappingCollection) {
  160. if (mapping.DestinationColumn == (string) row ["ColumnName"]) {
  161. flag = true;
  162. break;
  163. }
  164. }
  165. }
  166. if (flag == false)
  167. break;
  168. }
  169. if ((bool)row ["IsReadOnly"]) {
  170. if (ordinalMapping)
  171. value = false;
  172. else
  173. break;
  174. }
  175. SqlParameter param = new SqlParameter ((string) row ["ColumnName"],
  176. ((SqlDbType) row ["ProviderType"]));
  177. param.Value = value;
  178. if ((int)row ["ColumnSize"] != -1) {
  179. param.Size = (int) row ["ColumnSize"];
  180. }
  181. tmpCmd.Parameters.Add (param);
  182. break;
  183. }
  184. i++;
  185. }
  186. flag = false;
  187. bool insertSt = false;
  188. foreach (DataRow row in colMetaData.Rows) {
  189. if (_columnMappingCollection.Count > 0) {
  190. i = 0;
  191. insertSt = false;
  192. foreach (SqlParameter param in tmpCmd.Parameters) {
  193. if (ordinalMapping) {
  194. foreach (SqlBulkCopyColumnMapping mapping
  195. in _columnMappingCollection) {
  196. if (mapping.DestinationOrdinal == i && param.Value == null) {
  197. insertSt = true;
  198. }
  199. }
  200. } else {
  201. foreach (SqlBulkCopyColumnMapping mapping
  202. in _columnMappingCollection) {
  203. if (mapping.DestinationColumn == param.ParameterName &&
  204. (string)row ["ColumnName"] == param.ParameterName) {
  205. insertSt = true;
  206. param.Value = null;
  207. }
  208. }
  209. }
  210. i++;
  211. if (insertSt == true)
  212. break;
  213. }
  214. if (insertSt == false)
  215. continue;
  216. }
  217. if ((bool)row ["IsReadOnly"]) {
  218. continue;
  219. }
  220. string columnInfo = "";
  221. if ((int)row ["ColumnSize"] != -1) {
  222. columnInfo = string.Format ("{0}({1})",
  223. (SqlDbType) row ["ProviderType"],
  224. row ["ColumnSize"]);
  225. } else {
  226. columnInfo = string.Format ("{0}", (SqlDbType) row ["ProviderType"]);
  227. }
  228. if (flag)
  229. statement += ", ";
  230. string columnName = (string) row ["ColumnName"];
  231. statement += string.Format ("[{0}] {1}", columnName, columnInfo);
  232. if (flag == false)
  233. flag = true;
  234. if (tableCollations != null) {
  235. foreach (DataRow collationRow in tableCollations.Rows) {
  236. if ((string)collationRow ["name"] == columnName) {
  237. statement += string.Format (" COLLATE {0}", collationRow ["collation"]);
  238. break;
  239. }
  240. }
  241. }
  242. }
  243. return statement;
  244. }
  245. private void ValidateColumnMapping (DataTable table, DataTable tableCollations)
  246. {
  247. foreach (SqlBulkCopyColumnMapping _columnMapping in _columnMappingCollection) {
  248. if (ordinalMapping == false &&
  249. (_columnMapping.DestinationColumn == String.Empty ||
  250. _columnMapping.SourceColumn == String.Empty))
  251. throw new InvalidOperationException ("Mappings must be either all null or ordinal");
  252. if (ordinalMapping &&
  253. (_columnMapping.DestinationOrdinal == -1 ||
  254. _columnMapping.SourceOrdinal == -1))
  255. throw new InvalidOperationException ("Mappings must be either all null or ordinal");
  256. bool flag = false;
  257. if (ordinalMapping == false) {
  258. foreach (DataRow row in tableCollations.Rows) {
  259. if ((string)row ["name"] == _columnMapping.DestinationColumn) {
  260. flag = true;
  261. break;
  262. }
  263. }
  264. if (flag == false)
  265. throw new InvalidOperationException ("ColumnMapping does not match");
  266. flag = false;
  267. foreach (DataColumn col in table.Columns) {
  268. if (col.ColumnName == _columnMapping.SourceColumn) {
  269. flag = true;
  270. break;
  271. }
  272. }
  273. if (flag == false)
  274. throw new InvalidOperationException ("ColumnName " +
  275. _columnMapping.SourceColumn +
  276. " does not match");
  277. } else {
  278. if (_columnMapping.DestinationOrdinal >= tableCollations.Rows.Count)
  279. throw new InvalidOperationException ("ColumnMapping does not match");
  280. }
  281. }
  282. }
  283. private void BulkCopyToServer (DataTable table, DataRowState state)
  284. {
  285. if (connection == null || connection.State == ConnectionState.Closed)
  286. throw new InvalidOperationException ("This method should not be called on a closed connection");
  287. if (_destinationTableName == null)
  288. throw new ArgumentNullException ("DestinationTableName");
  289. if (identityInsert) {
  290. SqlCommand cmd = new SqlCommand ("set identity_insert " +
  291. table.TableName + " on",
  292. connection);
  293. cmd.ExecuteScalar ();
  294. }
  295. DataTable [] columnMetaDataTables = GetColumnMetaData ();
  296. DataTable colMetaData = columnMetaDataTables [0];
  297. DataTable tableCollations = columnMetaDataTables [1];
  298. if (_columnMappingCollection.Count > 0) {
  299. if (_columnMappingCollection [0].SourceOrdinal != -1)
  300. ordinalMapping = true;
  301. ValidateColumnMapping (table, tableCollations);
  302. }
  303. SqlCommand tmpCmd = new SqlCommand ();
  304. TdsBulkCopy blkCopy = new TdsBulkCopy ((Tds)connection.Tds);
  305. if (((Tds)connection.Tds).TdsVersion >= TdsVersion.tds70) {
  306. string statement = "insert bulk " + DestinationTableName + " (";
  307. statement += GenerateColumnMetaData (tmpCmd, colMetaData, tableCollations);
  308. statement += ")";
  309. blkCopy.SendColumnMetaData (statement);
  310. }
  311. blkCopy.BulkCopyStart (tmpCmd.Parameters.MetaParameters);
  312. long noRowsCopied = 0;
  313. foreach (DataRow row in table.Rows) {
  314. if (row.RowState == DataRowState.Deleted)
  315. continue; // Don't copy the row that's in deleted state
  316. if (state != 0 && row.RowState != state)
  317. continue;
  318. bool isNewRow = true;
  319. int i = 0;
  320. foreach (SqlParameter param in tmpCmd.Parameters) {
  321. int size = 0;
  322. object rowToCopy = null;
  323. if (_columnMappingCollection.Count > 0) {
  324. if (ordinalMapping) {
  325. foreach (SqlBulkCopyColumnMapping mapping
  326. in _columnMappingCollection) {
  327. if (mapping.DestinationOrdinal == i && param.Value == null) {
  328. rowToCopy = row [mapping.SourceOrdinal];
  329. SqlParameter parameter = new SqlParameter (mapping.SourceOrdinal.ToString (),
  330. rowToCopy);
  331. if (param.MetaParameter.TypeName != parameter.MetaParameter.TypeName) {
  332. parameter.SqlDbType = param.SqlDbType;
  333. rowToCopy = parameter.Value = parameter.ConvertToFrameworkType (rowToCopy);
  334. }
  335. string colType = string.Format ("{0}", parameter.MetaParameter.TypeName);
  336. if (colType == "nvarchar") {
  337. if (row [i] != null) {
  338. size = ((string) parameter.Value).Length;
  339. size <<= 1;
  340. }
  341. } else {
  342. size = parameter.Size;
  343. }
  344. break;
  345. }
  346. }
  347. } else {
  348. foreach (SqlBulkCopyColumnMapping mapping
  349. in _columnMappingCollection) {
  350. if (mapping.DestinationColumn == param.ParameterName) {
  351. rowToCopy = row [mapping.SourceColumn];
  352. SqlParameter parameter = new SqlParameter (mapping.SourceColumn, rowToCopy);
  353. if (param.MetaParameter.TypeName != parameter.MetaParameter.TypeName) {
  354. parameter.SqlDbType = param.SqlDbType;
  355. rowToCopy = parameter.Value = parameter.ConvertToFrameworkType (rowToCopy);
  356. }
  357. string colType = string.Format ("{0}", parameter.MetaParameter.TypeName);
  358. if (colType == "nvarchar") {
  359. if (row [mapping.SourceColumn] != null) {
  360. size = ((string) rowToCopy).Length;
  361. size <<= 1;
  362. }
  363. } else {
  364. size = parameter.Size;
  365. }
  366. break;
  367. }
  368. }
  369. }
  370. i++;
  371. } else {
  372. rowToCopy = row [param.ParameterName];
  373. string colType = param.MetaParameter.TypeName;
  374. /*
  375. If column type is SqlDbType.NVarChar the size of parameter is multiplied by 2
  376. FIXME: Need to check for other types
  377. */
  378. if (colType == "nvarchar") {
  379. size = ((string) row [param.ParameterName]).Length;
  380. size <<= 1;
  381. } else {
  382. size = param.Size;
  383. }
  384. }
  385. if (rowToCopy == null)
  386. continue;
  387. blkCopy.BulkCopyData (rowToCopy, size, isNewRow);
  388. if (isNewRow)
  389. isNewRow = false;
  390. } // foreach (SqlParameter)
  391. if (_notifyAfter > 0) {
  392. noRowsCopied ++;
  393. if (noRowsCopied >= _notifyAfter) {
  394. RowsCopied (noRowsCopied);
  395. noRowsCopied = 0;
  396. }
  397. }
  398. } // foreach (DataRow)
  399. blkCopy.BulkCopyEnd ();
  400. }
  401. public void WriteToServer (DataRow [] rows)
  402. {
  403. if (rows == null)
  404. throw new ArgumentNullException ("rows");
  405. DataTable table = new DataTable (rows [0].Table.TableName);
  406. foreach (DataColumn col in rows [0].Table.Columns) {
  407. DataColumn tmpCol = new DataColumn (col.ColumnName, col.DataType);
  408. table.Columns.Add (tmpCol);
  409. }
  410. foreach (DataRow row in rows) {
  411. DataRow tmpRow = table.NewRow ();
  412. for (int i = 0; i < table.Columns.Count; i++) {
  413. tmpRow [i] = row [i];
  414. }
  415. table.Rows.Add (tmpRow);
  416. }
  417. BulkCopyToServer (table, 0);
  418. }
  419. public void WriteToServer (DataTable table)
  420. {
  421. BulkCopyToServer (table, 0);
  422. }
  423. public void WriteToServer (IDataReader reader)
  424. {
  425. DataTable table = new DataTable ();
  426. SqlDataAdapter adapter = new SqlDataAdapter ();
  427. adapter.FillInternal (table, reader);
  428. BulkCopyToServer (table, 0);
  429. }
  430. public void WriteToServer (DataTable table, DataRowState rowState)
  431. {
  432. BulkCopyToServer (table, rowState);
  433. }
  434. private void RowsCopied (long rowsCopied)
  435. {
  436. SqlRowsCopiedEventArgs e = new SqlRowsCopiedEventArgs (rowsCopied);
  437. if (null != SqlRowsCopied) {
  438. SqlRowsCopied (this, e);
  439. }
  440. }
  441. #endregion
  442. #region Events
  443. public event SqlRowsCopiedEventHandler SqlRowsCopied;
  444. #endregion
  445. void IDisposable.Dispose ()
  446. {
  447. //throw new NotImplementedException ();
  448. if (isLocalConnection) {
  449. Close ();
  450. connection = null;
  451. }
  452. }
  453. }
  454. }
  455. #endif