SqlBulkCopy.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. /// <summary>Efficient way to bulk load SQL Server table with several data rows at once</summary>
  38. public sealed class SqlBulkCopy : IDisposable
  39. {
  40. #region Constants
  41. private const string transConflictMessage = "Must not specify SqlBulkCopyOptions.UseInternalTransaction " +
  42. "and pass an external Transaction at the same time.";
  43. private const SqlBulkCopyOptions insertModifiers =
  44. SqlBulkCopyOptions.CheckConstraints | SqlBulkCopyOptions.TableLock |
  45. SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.FireTriggers;
  46. #endregion
  47. #region Fields
  48. private int _batchSize = 0;
  49. private int _notifyAfter = 0;
  50. private int _bulkCopyTimeout = 0;
  51. private SqlBulkCopyColumnMappingCollection _columnMappingCollection = new SqlBulkCopyColumnMappingCollection ();
  52. private string _destinationTableName = null;
  53. private bool ordinalMapping = false;
  54. private bool sqlRowsCopied = false;
  55. private bool isLocalConnection = false;
  56. private SqlConnection connection;
  57. private SqlTransaction externalTransaction;
  58. private SqlBulkCopyOptions copyOptions = SqlBulkCopyOptions.Default;
  59. #endregion
  60. #region Constructors
  61. public SqlBulkCopy (SqlConnection connection)
  62. {
  63. if (connection == null) {
  64. throw new ArgumentNullException("connection");
  65. }
  66. this.connection = connection;
  67. }
  68. public SqlBulkCopy (string connectionString)
  69. {
  70. if (connectionString == null) {
  71. throw new ArgumentNullException("connectionString");
  72. }
  73. this.connection = new SqlConnection (connectionString);
  74. isLocalConnection = true;
  75. }
  76. [MonoTODO]
  77. public SqlBulkCopy (string connectionString, SqlBulkCopyOptions copyOptions)
  78. {
  79. if (connectionString == null) {
  80. throw new ArgumentNullException ("connectionString");
  81. }
  82. this.connection = new SqlConnection (connectionString);
  83. isLocalConnection = true;
  84. if ((copyOptions & SqlBulkCopyOptions.UseInternalTransaction) == SqlBulkCopyOptions.UseInternalTransaction)
  85. throw new NotImplementedException ("We don't know how to process UseInternalTransaction option.");
  86. this.copyOptions = copyOptions;
  87. }
  88. [MonoTODO]
  89. public SqlBulkCopy (SqlConnection connection, SqlBulkCopyOptions copyOptions, SqlTransaction externalTransaction)
  90. {
  91. if (connection == null) {
  92. throw new ArgumentNullException ("connection");
  93. }
  94. this.connection = connection;
  95. this.copyOptions = copyOptions;
  96. if ((copyOptions & SqlBulkCopyOptions.UseInternalTransaction) == SqlBulkCopyOptions.UseInternalTransaction) {
  97. if (externalTransaction != null)
  98. throw new ArgumentException (transConflictMessage);
  99. }
  100. else
  101. this.externalTransaction = externalTransaction;
  102. if ((copyOptions & SqlBulkCopyOptions.UseInternalTransaction) == SqlBulkCopyOptions.UseInternalTransaction)
  103. throw new NotImplementedException ("We don't know how to process UseInternalTransaction option.");
  104. this.copyOptions = copyOptions;
  105. }
  106. #endregion
  107. #region Properties
  108. public int BatchSize {
  109. get { return _batchSize; }
  110. set { _batchSize = value; }
  111. }
  112. public int BulkCopyTimeout {
  113. get { return _bulkCopyTimeout; }
  114. set { _bulkCopyTimeout = value; }
  115. }
  116. public SqlBulkCopyColumnMappingCollection ColumnMappings {
  117. get { return _columnMappingCollection; }
  118. }
  119. public string DestinationTableName {
  120. get { return _destinationTableName; }
  121. set { _destinationTableName = value; }
  122. }
  123. public int NotifyAfter {
  124. get { return _notifyAfter; }
  125. set {
  126. if (value < 0)
  127. throw new ArgumentOutOfRangeException ("NotifyAfter should be greater than or equal to 0");
  128. _notifyAfter = value;
  129. }
  130. }
  131. #endregion
  132. #region Methods
  133. public void Close ()
  134. {
  135. if (sqlRowsCopied == true) {
  136. throw new InvalidOperationException ("Close should not be called from SqlRowsCopied event");
  137. }
  138. if (connection == null || connection.State == ConnectionState.Closed) {
  139. return;
  140. }
  141. connection.Close ();
  142. }
  143. private DataTable [] GetColumnMetaData ()
  144. {
  145. DataTable [] columnMetaDataTables = new DataTable [2];
  146. SqlCommand cmd = new SqlCommand ("select @@trancount; " +
  147. "set fmtonly on select * from " +
  148. DestinationTableName + " set fmtonly off;" +
  149. "exec sp_tablecollations_90 '" +
  150. DestinationTableName + "'",
  151. connection);
  152. SqlDataReader reader = cmd.ExecuteReader ();
  153. int i = 0; // Skipping 1st result
  154. do {
  155. if (i == 1) {
  156. columnMetaDataTables [i - 1] = reader.GetSchemaTable ();
  157. } else if (i == 2) {
  158. SqlDataAdapter adapter = new SqlDataAdapter ();
  159. adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
  160. columnMetaDataTables [i - 1] = new DataTable ();
  161. adapter.FillInternal (columnMetaDataTables [i - 1], reader);
  162. }
  163. i++;
  164. } while (reader.IsClosed == false && reader.NextResult());
  165. reader.Close ();
  166. return columnMetaDataTables;
  167. }
  168. private string GenerateColumnMetaData (SqlCommand tmpCmd, DataTable colMetaData, DataTable tableCollations)
  169. {
  170. bool flag = false;
  171. string statement = "";
  172. int i = 0;
  173. foreach (DataRow row in colMetaData.Rows) {
  174. flag = false;
  175. foreach (DataColumn col in colMetaData.Columns) { // FIXME: This line not required, remove later
  176. object value = null;
  177. if (_columnMappingCollection.Count > 0) {
  178. if (ordinalMapping) {
  179. foreach (SqlBulkCopyColumnMapping mapping
  180. in _columnMappingCollection) {
  181. if (mapping.DestinationOrdinal == i) {
  182. flag = true;
  183. break;
  184. }
  185. }
  186. } else {
  187. foreach (SqlBulkCopyColumnMapping mapping
  188. in _columnMappingCollection) {
  189. if (mapping.DestinationColumn == (string) row ["ColumnName"]) {
  190. flag = true;
  191. break;
  192. }
  193. }
  194. }
  195. if (flag == false)
  196. break;
  197. }
  198. if ((bool)row ["IsReadOnly"]) {
  199. if (ordinalMapping)
  200. value = false;
  201. else
  202. break;
  203. }
  204. SqlParameter param = new SqlParameter ((string) row ["ColumnName"],
  205. ((SqlDbType) row ["ProviderType"]));
  206. param.Value = value;
  207. if ((int)row ["ColumnSize"] != -1) {
  208. param.Size = (int) row ["ColumnSize"];
  209. }
  210. tmpCmd.Parameters.Add (param);
  211. break;
  212. }
  213. i++;
  214. }
  215. flag = false;
  216. bool insertSt = false;
  217. foreach (DataRow row in colMetaData.Rows) {
  218. if (_columnMappingCollection.Count > 0) {
  219. i = 0;
  220. insertSt = false;
  221. foreach (SqlParameter param in tmpCmd.Parameters) {
  222. if (ordinalMapping) {
  223. foreach (SqlBulkCopyColumnMapping mapping
  224. in _columnMappingCollection) {
  225. if (mapping.DestinationOrdinal == i && param.Value == null) {
  226. insertSt = true;
  227. }
  228. }
  229. } else {
  230. foreach (SqlBulkCopyColumnMapping mapping
  231. in _columnMappingCollection) {
  232. if (mapping.DestinationColumn == param.ParameterName &&
  233. (string)row ["ColumnName"] == param.ParameterName) {
  234. insertSt = true;
  235. param.Value = null;
  236. }
  237. }
  238. }
  239. i++;
  240. if (insertSt == true)
  241. break;
  242. }
  243. if (insertSt == false)
  244. continue;
  245. }
  246. if ((bool)row ["IsReadOnly"]) {
  247. continue;
  248. }
  249. string columnInfo = "";
  250. if ((int)row ["ColumnSize"] != -1) {
  251. columnInfo = string.Format ("{0}({1})",
  252. (SqlDbType) row ["ProviderType"],
  253. row ["ColumnSize"]);
  254. } else {
  255. columnInfo = string.Format ("{0}", (SqlDbType) row ["ProviderType"]);
  256. }
  257. if (flag)
  258. statement += ", ";
  259. string columnName = (string) row ["ColumnName"];
  260. statement += string.Format ("[{0}] {1}", columnName, columnInfo);
  261. if (flag == false)
  262. flag = true;
  263. if (tableCollations != null) {
  264. foreach (DataRow collationRow in tableCollations.Rows) {
  265. if ((string)collationRow ["name"] == columnName) {
  266. statement += string.Format (" COLLATE {0}", collationRow ["collation"]);
  267. break;
  268. }
  269. }
  270. }
  271. }
  272. return statement;
  273. }
  274. private void ValidateColumnMapping (DataTable table, DataTable tableCollations)
  275. {
  276. foreach (SqlBulkCopyColumnMapping _columnMapping in _columnMappingCollection) {
  277. if (ordinalMapping == false &&
  278. (_columnMapping.DestinationColumn == String.Empty ||
  279. _columnMapping.SourceColumn == String.Empty))
  280. throw new InvalidOperationException ("Mappings must be either all null or ordinal");
  281. if (ordinalMapping &&
  282. (_columnMapping.DestinationOrdinal == -1 ||
  283. _columnMapping.SourceOrdinal == -1))
  284. throw new InvalidOperationException ("Mappings must be either all null or ordinal");
  285. bool flag = false;
  286. if (ordinalMapping == false) {
  287. foreach (DataRow row in tableCollations.Rows) {
  288. if ((string)row ["name"] == _columnMapping.DestinationColumn) {
  289. flag = true;
  290. break;
  291. }
  292. }
  293. if (flag == false)
  294. throw new InvalidOperationException ("ColumnMapping does not match");
  295. flag = false;
  296. foreach (DataColumn col in table.Columns) {
  297. if (col.ColumnName == _columnMapping.SourceColumn) {
  298. flag = true;
  299. break;
  300. }
  301. }
  302. if (flag == false)
  303. throw new InvalidOperationException ("ColumnName " +
  304. _columnMapping.SourceColumn +
  305. " does not match");
  306. } else {
  307. if (_columnMapping.DestinationOrdinal >= tableCollations.Rows.Count)
  308. throw new InvalidOperationException ("ColumnMapping does not match");
  309. }
  310. }
  311. }
  312. private void BulkCopyToServer (DataTable table, DataRowState state)
  313. {
  314. if (connection == null || connection.State == ConnectionState.Closed)
  315. throw new InvalidOperationException ("This method should not be called on a closed connection");
  316. if (_destinationTableName == null)
  317. throw new ArgumentNullException ("DestinationTableName");
  318. if (isLocalConnection && connection.State != ConnectionState.Open)
  319. connection.Open();
  320. if ((copyOptions & SqlBulkCopyOptions.KeepIdentity) == SqlBulkCopyOptions.KeepIdentity) {
  321. SqlCommand cmd = new SqlCommand ("set identity_insert " +
  322. table.TableName + " on",
  323. connection);
  324. cmd.ExecuteScalar ();
  325. }
  326. DataTable [] columnMetaDataTables = GetColumnMetaData ();
  327. DataTable colMetaData = columnMetaDataTables [0];
  328. DataTable tableCollations = columnMetaDataTables [1];
  329. if (_columnMappingCollection.Count > 0) {
  330. if (_columnMappingCollection [0].SourceOrdinal != -1)
  331. ordinalMapping = true;
  332. ValidateColumnMapping (table, tableCollations);
  333. }
  334. SqlCommand tmpCmd = new SqlCommand ();
  335. TdsBulkCopy blkCopy = new TdsBulkCopy ((Tds)connection.Tds);
  336. if (((Tds)connection.Tds).TdsVersion >= TdsVersion.tds70) {
  337. string statement = "insert bulk " + DestinationTableName + " (";
  338. statement += GenerateColumnMetaData (tmpCmd, colMetaData, tableCollations);
  339. statement += ")";
  340. #region Check requested options and add corresponding modifiers to the statement
  341. if ((copyOptions & insertModifiers) != SqlBulkCopyOptions.Default) {
  342. statement += " WITH (";
  343. bool commaRequired = false;
  344. if ((copyOptions & SqlBulkCopyOptions.CheckConstraints) == SqlBulkCopyOptions.CheckConstraints) {
  345. if (commaRequired)
  346. statement += ", ";
  347. statement += "CHECK_CONSTRAINTS";
  348. commaRequired = true;
  349. }
  350. if ((copyOptions & SqlBulkCopyOptions.TableLock) == SqlBulkCopyOptions.TableLock) {
  351. if (commaRequired)
  352. statement += ", ";
  353. statement += "TABLOCK";
  354. commaRequired = true;
  355. }
  356. if ((copyOptions & SqlBulkCopyOptions.KeepNulls) == SqlBulkCopyOptions.KeepNulls) {
  357. if (commaRequired)
  358. statement += ", ";
  359. statement += "KEEP_NULLS";
  360. commaRequired = true;
  361. }
  362. if ((copyOptions & SqlBulkCopyOptions.FireTriggers) == SqlBulkCopyOptions.FireTriggers) {
  363. if (commaRequired)
  364. statement += ", ";
  365. statement += "FIRE_TRIGGERS";
  366. commaRequired = true;
  367. }
  368. statement += ")";
  369. }
  370. #endregion Check requested options and add corresponding modifiers to the statement
  371. blkCopy.SendColumnMetaData (statement);
  372. }
  373. blkCopy.BulkCopyStart (tmpCmd.Parameters.MetaParameters);
  374. long noRowsCopied = 0;
  375. foreach (DataRow row in table.Rows) {
  376. if (row.RowState == DataRowState.Deleted)
  377. continue; // Don't copy the row that's in deleted state
  378. if (state != 0 && row.RowState != state)
  379. continue;
  380. bool isNewRow = true;
  381. int i = 0;
  382. foreach (SqlParameter param in tmpCmd.Parameters) {
  383. int size = 0;
  384. object rowToCopy = null;
  385. if (_columnMappingCollection.Count > 0) {
  386. if (ordinalMapping) {
  387. foreach (SqlBulkCopyColumnMapping mapping
  388. in _columnMappingCollection) {
  389. if (mapping.DestinationOrdinal == i && param.Value == null) {
  390. rowToCopy = row [mapping.SourceOrdinal];
  391. SqlParameter parameter = new SqlParameter (mapping.SourceOrdinal.ToString (),
  392. rowToCopy);
  393. if (param.MetaParameter.TypeName != parameter.MetaParameter.TypeName) {
  394. parameter.SqlDbType = param.SqlDbType;
  395. rowToCopy = parameter.Value = parameter.ConvertToFrameworkType (rowToCopy);
  396. }
  397. string colType = string.Format ("{0}", parameter.MetaParameter.TypeName);
  398. if (colType == "nvarchar") {
  399. if (row [i] != null) {
  400. size = ((string) parameter.Value).Length;
  401. size <<= 1;
  402. }
  403. } else {
  404. size = parameter.Size;
  405. }
  406. break;
  407. }
  408. }
  409. } else {
  410. foreach (SqlBulkCopyColumnMapping mapping
  411. in _columnMappingCollection) {
  412. if (mapping.DestinationColumn == param.ParameterName) {
  413. rowToCopy = row [mapping.SourceColumn];
  414. SqlParameter parameter = new SqlParameter (mapping.SourceColumn, rowToCopy);
  415. if (param.MetaParameter.TypeName != parameter.MetaParameter.TypeName) {
  416. parameter.SqlDbType = param.SqlDbType;
  417. rowToCopy = parameter.Value = parameter.ConvertToFrameworkType (rowToCopy);
  418. }
  419. string colType = string.Format ("{0}", parameter.MetaParameter.TypeName);
  420. if (colType == "nvarchar") {
  421. if (row [mapping.SourceColumn] != null) {
  422. size = ((string) rowToCopy).Length;
  423. size <<= 1;
  424. }
  425. } else {
  426. size = parameter.Size;
  427. }
  428. break;
  429. }
  430. }
  431. }
  432. i++;
  433. } else {
  434. rowToCopy = row [param.ParameterName];
  435. string colType = param.MetaParameter.TypeName;
  436. /*
  437. If column type is SqlDbType.NVarChar the size of parameter is multiplied by 2
  438. FIXME: Need to check for other types
  439. */
  440. if (colType == "nvarchar") {
  441. size = ((string) row [param.ParameterName]).Length;
  442. size <<= 1;
  443. } else {
  444. size = param.Size;
  445. }
  446. }
  447. if (rowToCopy == null)
  448. continue;
  449. blkCopy.BulkCopyData (rowToCopy, size, isNewRow);
  450. if (isNewRow)
  451. isNewRow = false;
  452. } // foreach (SqlParameter)
  453. if (_notifyAfter > 0) {
  454. noRowsCopied ++;
  455. if (noRowsCopied >= _notifyAfter) {
  456. RowsCopied (noRowsCopied);
  457. noRowsCopied = 0;
  458. }
  459. }
  460. } // foreach (DataRow)
  461. blkCopy.BulkCopyEnd ();
  462. }
  463. public void WriteToServer (DataRow [] rows)
  464. {
  465. if (rows == null)
  466. throw new ArgumentNullException ("rows");
  467. DataTable table = new DataTable (rows [0].Table.TableName);
  468. foreach (DataColumn col in rows [0].Table.Columns) {
  469. DataColumn tmpCol = new DataColumn (col.ColumnName, col.DataType);
  470. table.Columns.Add (tmpCol);
  471. }
  472. foreach (DataRow row in rows) {
  473. DataRow tmpRow = table.NewRow ();
  474. for (int i = 0; i < table.Columns.Count; i++) {
  475. tmpRow [i] = row [i];
  476. }
  477. table.Rows.Add (tmpRow);
  478. }
  479. BulkCopyToServer (table, 0);
  480. }
  481. public void WriteToServer (DataTable table)
  482. {
  483. BulkCopyToServer (table, 0);
  484. }
  485. public void WriteToServer (IDataReader reader)
  486. {
  487. DataTable table = new DataTable ();
  488. SqlDataAdapter adapter = new SqlDataAdapter ();
  489. adapter.FillInternal (table, reader);
  490. BulkCopyToServer (table, 0);
  491. }
  492. public void WriteToServer (DataTable table, DataRowState rowState)
  493. {
  494. BulkCopyToServer (table, rowState);
  495. }
  496. private void RowsCopied (long rowsCopied)
  497. {
  498. SqlRowsCopiedEventArgs e = new SqlRowsCopiedEventArgs (rowsCopied);
  499. if (null != SqlRowsCopied) {
  500. SqlRowsCopied (this, e);
  501. }
  502. }
  503. #endregion
  504. #region Events
  505. public event SqlRowsCopiedEventHandler SqlRowsCopied;
  506. #endregion
  507. void IDisposable.Dispose ()
  508. {
  509. //throw new NotImplementedException ();
  510. if (isLocalConnection) {
  511. Close ();
  512. connection = null;
  513. }
  514. }
  515. }
  516. }
  517. #endif