1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
|
// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Collections;
using System.Text;
using MySql.Data.Common;
using System.ComponentModel;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using MySql.Data.MySqlClient.Properties;
#if !CF
using System.Transactions;
#endif
namespace MySql.Data.MySqlClient
{
/// <include file='docs/mysqlcommand.xml' path='docs/ClassSummary/*'/>
#if !CF
[System.Drawing.ToolboxBitmap(typeof(MySqlCommand), "MySqlClient.resources.command.bmp")]
[System.ComponentModel.DesignerCategory("Code")]
#endif
public sealed class MySqlCommand : DbCommand, ICloneable
{
MySqlConnection connection;
MySqlTransaction curTransaction;
string cmdText;
CommandType cmdType;
long updatedRowCount;
UpdateRowSource updatedRowSource;
MySqlParameterCollection parameters;
private IAsyncResult asyncResult;
private bool designTimeVisible;
internal Int64 lastInsertedId;
private PreparableStatement statement;
private int commandTimeout;
private bool canceled;
private bool resetSqlSelect;
List<MySqlCommand> batch;
private string batchableCommandText;
CommandTimer commandTimer;
private bool useDefaultTimeout;
private bool shouldCache;
private int cacheAge;
private bool internallyCreated;
/// <include file='docs/mysqlcommand.xml' path='docs/ctor1/*'/>
public MySqlCommand()
{
designTimeVisible = true;
cmdType = CommandType.Text;
parameters = new MySqlParameterCollection(this);
updatedRowSource = UpdateRowSource.Both;
cmdText = String.Empty;
useDefaultTimeout = true;
}
/// <include file='docs/mysqlcommand.xml' path='docs/ctor2/*'/>
public MySqlCommand(string cmdText)
: this()
{
CommandText = cmdText;
}
/// <include file='docs/mysqlcommand.xml' path='docs/ctor3/*'/>
public MySqlCommand(string cmdText, MySqlConnection connection)
: this(cmdText)
{
Connection = connection;
}
/// <include file='docs/mysqlcommand.xml' path='docs/ctor4/*'/>
public MySqlCommand(string cmdText, MySqlConnection connection,
MySqlTransaction transaction)
:
this(cmdText, connection)
{
curTransaction = transaction;
}
#region Properties
/// <include file='docs/mysqlcommand.xml' path='docs/LastInseredId/*'/>
#if !CF
[Browsable(false)]
#endif
public Int64 LastInsertedId
{
get { return lastInsertedId; }
}
/// <include file='docs/mysqlcommand.xml' path='docs/CommandText/*'/>
#if !CF
[Category("Data")]
[Description("Command text to execute")]
[Editor("MySql.Data.Common.Design.SqlCommandTextEditor,MySqlClient.Design", typeof(System.Drawing.Design.UITypeEditor))]
#endif
public override string CommandText
{
get { return cmdText; }
set
{
cmdText = value;
statement = null;
batchableCommandText = null;
if (cmdText != null && cmdText.EndsWith("DEFAULT VALUES"))
{
cmdText = cmdText.Substring(0, cmdText.Length - 14);
cmdText = cmdText + "() VALUES ()";
}
}
}
/// <include file='docs/mysqlcommand.xml' path='docs/CommandTimeout/*'/>
#if !CF
[Category("Misc")]
[Description("Time to wait for command to execute")]
[DefaultValue(30)]
#endif
public override int CommandTimeout
{
get { return useDefaultTimeout ? 30 : commandTimeout; }
set
{
if (commandTimeout < 0)
throw new ArgumentException("Command timeout must not be negative");
// Timeout in milliseconds should not exceed maximum for 32 bit
// signed integer (~24 days), because underlying driver (and streams)
// use milliseconds expressed ints for timeout values.
// Hence, truncate the value.
int timeout = Math.Min(value, Int32.MaxValue / 1000);
if (timeout != value)
{
MySqlTrace.LogWarning(connection.ServerThread,
"Command timeout value too large ("
+ value + " seconds). Changed to max. possible value ("
+ timeout + " seconds)");
}
commandTimeout = timeout;
useDefaultTimeout = false;
}
}
/// <include file='docs/mysqlcommand.xml' path='docs/CommandType/*'/>
#if !CF
[Category("Data")]
#endif
public override CommandType CommandType
{
get { return cmdType; }
set { cmdType = value; }
}
/// <include file='docs/mysqlcommand.xml' path='docs/IsPrepared/*'/>
#if !CF
[Browsable(false)]
#endif
public bool IsPrepared
{
get { return statement != null && statement.IsPrepared; }
}
/// <include file='docs/mysqlcommand.xml' path='docs/Connection/*'/>
#if !CF
[Category("Behavior")]
[Description("Connection used by the command")]
#endif
public new MySqlConnection Connection
{
get { return connection; }
set
{
/*
* The connection is associated with the transaction
* so set the transaction object to return a null reference if the connection
* is reset.
*/
if (connection != value)
Transaction = null;
connection = value;
// if the user has not already set the command timeout, then
// take the default from the connection
if (connection != null)
{
if (useDefaultTimeout)
{
commandTimeout = (int)connection.Settings.DefaultCommandTimeout;
useDefaultTimeout = false;
}
EnableCaching = connection.Settings.TableCaching;
CacheAge = connection.Settings.DefaultTableCacheAge;
}
}
}
/// <include file='docs/mysqlcommand.xml' path='docs/Parameters/*'/>
#if !CF
[Category("Data")]
[Description("The parameters collection")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
#endif
public new MySqlParameterCollection Parameters
{
get { return parameters; }
}
/// <include file='docs/mysqlcommand.xml' path='docs/Transaction/*'/>
#if !CF
[Browsable(false)]
#endif
public new MySqlTransaction Transaction
{
get { return curTransaction; }
set { curTransaction = value; }
}
public bool EnableCaching
{
get { return shouldCache; }
set { shouldCache = value; }
}
public int CacheAge
{
get { return cacheAge; }
set { cacheAge = value; }
}
/* /// <include file='docs/mysqlcommand.xml' path='docs/UpdatedRowSource/*'/>
#if !CF
[Category("Behavior")]
#endif
public override UpdateRowSource UpdatedRowSource
{
get { return updatedRowSource; }
set { updatedRowSource = value; }
}*/
internal List<MySqlCommand> Batch
{
get { return batch; }
}
internal bool Canceled
{
get { return canceled; }
}
internal string BatchableCommandText
{
get { return batchableCommandText; }
}
internal bool InternallyCreated
{
get { return internallyCreated; }
set { internallyCreated = value; }
}
#endregion
#region Methods
/// <summary>
/// Attempts to cancel the execution of a currently active command
/// </summary>
/// <remarks>
/// Cancelling a currently active query only works with MySQL versions 5.0.0 and higher.
/// </remarks>
public override void Cancel()
{
connection.CancelQuery(connection.ConnectionTimeout);
canceled = true;
}
/// <summary>
/// Creates a new instance of a <see cref="MySqlParameter"/> object.
/// </summary>
/// <remarks>
/// This method is a strongly-typed version of <see cref="IDbCommand.CreateParameter"/>.
/// </remarks>
/// <returns>A <see cref="MySqlParameter"/> object.</returns>
///
public new MySqlParameter CreateParameter()
{
return (MySqlParameter)CreateDbParameter();
}
/// <summary>
/// Check the connection to make sure
/// - it is open
/// - it is not currently being used by a reader
/// - and we have the right version of MySQL for the requested command type
/// </summary>
private void CheckState()
{
// There must be a valid and open connection.
if (connection == null)
throw new InvalidOperationException("Connection must be valid and open.");
if (connection.State != ConnectionState.Open && !connection.SoftClosed)
throw new InvalidOperationException("Connection must be valid and open.");
// Data readers have to be closed first
if (connection.IsInUse && !this.internallyCreated)
throw new MySqlException("There is already an open DataReader associated with this Connection which must be closed first.");
}
/// <include file='docs/mysqlcommand.xml' path='docs/ExecuteNonQuery/*'/>
public override int ExecuteNonQuery()
{
using (MySqlDataReader reader = ExecuteReader())
{
reader.Close();
return reader.RecordsAffected;
}
}
internal void ClearCommandTimer()
{
if (commandTimer != null)
{
commandTimer.Dispose();
commandTimer = null;
}
}
internal void Close(MySqlDataReader reader)
{
if (statement != null)
statement.Close(reader);
ResetSqlSelectLimit();
if (statement != null && connection != null && connection.driver != null)
connection.driver.CloseQuery(connection, statement.StatementId);
ClearCommandTimer();
}
/// <summary>
/// Reset reader to null, to avoid "There is already an open data reader"
/// on the next ExecuteReader(). Used in error handling scenarios.
/// </summary>
private void ResetReader()
{
if (connection != null && connection.Reader != null)
{
connection.Reader.Close();
connection.Reader = null;
}
}
/// <summary>
/// Reset SQL_SELECT_LIMIT that could have been modified by CommandBehavior.
/// </summary>
internal void ResetSqlSelectLimit()
{
// if we are supposed to reset the sql select limit, do that here
if (resetSqlSelect)
{
resetSqlSelect = false;
MySqlCommand command = new MySqlCommand("SET SQL_SELECT_LIMIT=DEFAULT", connection);
command.internallyCreated = true;
command.ExecuteNonQuery();
}
}
/// <include file='docs/mysqlcommand.xml' path='docs/ExecuteReader/*'/>
public new MySqlDataReader ExecuteReader()
{
return ExecuteReader(CommandBehavior.Default);
}
/// <include file='docs/mysqlcommand.xml' path='docs/ExecuteReader1/*'/>
public new MySqlDataReader ExecuteReader (CommandBehavior behavior)
{
bool success = false;
CheckState();
Driver driver = connection.driver;
lock (driver)
{
// We have to recheck that there is no reader, after we got the lock
if (connection.Reader != null)
{
throw new MySqlException(Resources.DataReaderOpen);
}
#if !CF
System.Transactions.Transaction curTrans = System.Transactions.Transaction.Current;
if (curTrans != null)
{
bool inRollback = false;
if (driver.CurrentTransaction!= null)
inRollback = driver.CurrentTransaction.InRollback;
if (!inRollback)
{
TransactionStatus status = TransactionStatus.InDoubt;
try
{
// in some cases (during state transitions) this throws
// an exception. Ignore exceptions, we're only interested
// whether transaction was aborted or not.
status = curTrans.TransactionInformation.Status;
}
catch (TransactionException)
{
}
if (status == TransactionStatus.Aborted)
throw new TransactionAbortedException();
}
}
#endif
commandTimer = new CommandTimer(connection, CommandTimeout);
lastInsertedId = -1;
cmdText = cmdText.Trim();
if (String.IsNullOrEmpty(cmdText))
throw new InvalidOperationException(Resources.CommandTextNotInitialized);
string sql = cmdText.Trim(';');
if (CommandType == CommandType.TableDirect)
sql = "SELECT * FROM " + sql;
// if we are on a replicated connection, we are only allow readonly statements
if (connection.Settings.Replication && !InternallyCreated)
EnsureCommandIsReadOnly(sql);
if (statement == null || !statement.IsPrepared)
{
if (CommandType == CommandType.StoredProcedure)
statement = new StoredProcedure(this, sql);
else
statement = new PreparableStatement(this, sql);
}
// stored procs are the only statement type that need do anything during resolve
statement.Resolve(false);
// Now that we have completed our resolve step, we can handle our
// command behaviors
HandleCommandBehaviors(behavior);
updatedRowCount = -1;
try
{
MySqlDataReader reader = new MySqlDataReader(this, statement, behavior);
connection.Reader = reader;
canceled = false;
// execute the statement
statement.Execute();
// wait for data to return
reader.NextResult();
success = true;
return reader;
}
catch (TimeoutException tex)
{
connection.HandleTimeoutOrThreadAbort(tex);
throw; //unreached
}
catch (ThreadAbortException taex)
{
connection.HandleTimeoutOrThreadAbort(taex);
throw;
}
catch (IOException ioex)
{
connection.Abort(); // Closes connection without returning it to the pool
throw new MySqlException(Resources.FatalErrorDuringExecute, ioex);
}
catch (MySqlException ex)
{
if (ex.InnerException is TimeoutException)
throw; // already handled
try
{
ResetReader();
ResetSqlSelectLimit();
}
catch (Exception)
{
// Reset SqlLimit did not work, connection is hosed.
Connection.Abort();
throw new MySqlException(ex.Message, true, ex);
}
// if we caught an exception because of a cancel, then just return null
if (ex.IsQueryAborted)
return null;
if (ex.IsFatal)
Connection.Close();
if (ex.Number == 0)
throw new MySqlException(Resources.FatalErrorDuringExecute, ex);
throw;
}
finally
{
if (connection != null)
{
if (connection.Reader == null)
{
// Something went seriously wrong, and reader would not
// be able to clear timeout on closing.
// So we clear timeout here.
ClearCommandTimer();
}
if (!success)
{
// ExecuteReader failed.Close Reader and set to null to
// prevent subsequent errors with DataReaderOpen
ResetReader();
}
}
}
}
}
private void EnsureCommandIsReadOnly(string sql)
{
sql = sql.ToLower(CultureInfo.InvariantCulture);
if (!sql.StartsWith("select") && !sql.StartsWith("show"))
throw new MySqlException(Resources.ReplicatedConnectionsAllowOnlyReadonlyStatements);
if (sql.EndsWith("for update") || sql.EndsWith("lock in share mode"))
throw new MySqlException(Resources.ReplicatedConnectionsAllowOnlyReadonlyStatements);
}
/// <include file='docs/mysqlcommand.xml' path='docs/ExecuteScalar/*'/>
public override object ExecuteScalar()
{
lastInsertedId = -1;
object val = null;
using (MySqlDataReader reader = ExecuteReader())
{
if (reader.Read())
val = reader.GetValue(0);
}
return val;
}
private void HandleCommandBehaviors(CommandBehavior behavior)
{
if ((behavior & CommandBehavior.SchemaOnly) != 0)
{
new MySqlCommand("SET SQL_SELECT_LIMIT=0", connection).ExecuteNonQuery();
resetSqlSelect = true;
}
else if ((behavior & CommandBehavior.SingleRow) != 0)
{
new MySqlCommand("SET SQL_SELECT_LIMIT=1", connection).ExecuteNonQuery();
resetSqlSelect = true;
}
}
/// <include file='docs/mysqlcommand.xml' path='docs/Prepare2/*'/>
private void Prepare(int cursorPageSize)
{
using (new CommandTimer(Connection, CommandTimeout))
{
// if the length of the command text is zero, then just return
string psSQL = CommandText;
if (psSQL == null ||
psSQL.Trim().Length == 0)
return;
if (CommandType == CommandType.StoredProcedure)
statement = new StoredProcedure(this, CommandText);
else
statement = new PreparableStatement(this, CommandText);
statement.Resolve(true);
statement.Prepare();
}
}
/// <include file='docs/mysqlcommand.xml' path='docs/Prepare/*'/>
public override void Prepare()
{
if (connection == null)
throw new InvalidOperationException("The connection property has not been set.");
if (connection.State != ConnectionState.Open)
throw new InvalidOperationException("The connection is not open.");
if (connection.Settings.IgnorePrepare)
return;
Prepare(0);
}
#endregion
#region Async Methods
internal delegate object AsyncDelegate(int type, CommandBehavior behavior);
internal AsyncDelegate caller = null;
internal Exception thrownException;
internal object AsyncExecuteWrapper(int type, CommandBehavior behavior)
{
thrownException = null;
try
{
if (type == 1)
return ExecuteReader(behavior);
return ExecuteNonQuery();
}
catch (Exception ex)
{
thrownException = ex;
}
return null;
}
/// <summary>
/// Initiates the asynchronous execution of the SQL statement or stored procedure
/// that is described by this <see cref="MySqlCommand"/>, and retrieves one or more
/// result sets from the server.
/// </summary>
/// <returns>An <see cref="IAsyncResult"/> that can be used to poll, wait for results,
/// or both; this value is also needed when invoking EndExecuteReader,
/// which returns a <see cref="MySqlDataReader"/> instance that can be used to retrieve
/// the returned rows. </returns>
public IAsyncResult BeginExecuteReader()
{
return BeginExecuteReader(CommandBehavior.Default);
}
/// <summary>
/// Initiates the asynchronous execution of the SQL statement or stored procedure
/// that is described by this <see cref="MySqlCommand"/> using one of the
/// <b>CommandBehavior</b> values.
/// </summary>
/// <param name="behavior">One of the <see cref="CommandBehavior"/> values, indicating
/// options for statement execution and data retrieval.</param>
/// <returns>An <see cref="IAsyncResult"/> that can be used to poll, wait for results,
/// or both; this value is also needed when invoking EndExecuteReader,
/// which returns a <see cref="MySqlDataReader"/> instance that can be used to retrieve
/// the returned rows. </returns>
public IAsyncResult BeginExecuteReader(CommandBehavior behavior)
{
if (caller != null)
throw new MySqlException(Resources.UnableToStartSecondAsyncOp);
caller = new AsyncDelegate(AsyncExecuteWrapper);
asyncResult = caller.BeginInvoke(1, behavior, null, null);
return asyncResult;
}
/// <summary>
/// Finishes asynchronous execution of a SQL statement, returning the requested
/// <see cref="MySqlDataReader"/>.
/// </summary>
/// <param name="result">The <see cref="IAsyncResult"/> returned by the call to
/// <see cref="BeginExecuteReader()"/>.</param>
/// <returns>A <b>MySqlDataReader</b> object that can be used to retrieve the requested rows. </returns>
public MySqlDataReader EndExecuteReader(IAsyncResult result)
{
result.AsyncWaitHandle.WaitOne();
AsyncDelegate c = caller;
caller = null;
if (thrownException != null)
throw thrownException;
return (MySqlDataReader)c.EndInvoke(result);
}
/// <summary>
/// Initiates the asynchronous execution of the SQL statement or stored procedure
/// that is described by this <see cref="MySqlCommand"/>.
/// </summary>
/// <param name="callback">
/// An <see cref="AsyncCallback"/> delegate that is invoked when the command's
/// execution has completed. Pass a null reference (<b>Nothing</b> in Visual Basic)
/// to indicate that no callback is required.</param>
/// <param name="stateObject">A user-defined state object that is passed to the
/// callback procedure. Retrieve this object from within the callback procedure
/// using the <see cref="IAsyncResult.AsyncState"/> property.</param>
/// <returns>An <see cref="IAsyncResult"/> that can be used to poll or wait for results,
/// or both; this value is also needed when invoking <see cref="EndExecuteNonQuery"/>,
/// which returns the number of affected rows. </returns>
public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject)
{
if (caller != null)
throw new MySqlException(Resources.UnableToStartSecondAsyncOp);
caller = new AsyncDelegate(AsyncExecuteWrapper);
asyncResult = caller.BeginInvoke(2, CommandBehavior.Default,
callback, stateObject);
return asyncResult;
}
/// <summary>
/// Initiates the asynchronous execution of the SQL statement or stored procedure
/// that is described by this <see cref="MySqlCommand"/>.
/// </summary>
/// <returns>An <see cref="IAsyncResult"/> that can be used to poll or wait for results,
/// or both; this value is also needed when invoking <see cref="EndExecuteNonQuery"/>,
/// which returns the number of affected rows. </returns>
public IAsyncResult BeginExecuteNonQuery()
{
if (caller != null)
throw new MySqlException(Resources.UnableToStartSecondAsyncOp);
caller = new AsyncDelegate(AsyncExecuteWrapper);
asyncResult = caller.BeginInvoke(2, CommandBehavior.Default, null, null);
return asyncResult;
}
/// <summary>
/// Finishes asynchronous execution of a SQL statement.
/// </summary>
/// <param name="asyncResult">The <see cref="IAsyncResult"/> returned by the call
/// to <see cref="BeginExecuteNonQuery()"/>.</param>
/// <returns></returns>
public int EndExecuteNonQuery(IAsyncResult asyncResult)
{
asyncResult.AsyncWaitHandle.WaitOne();
AsyncDelegate c = caller;
caller = null;
if (thrownException != null)
throw thrownException;
return (int)c.EndInvoke(asyncResult);
}
#endregion
#region Private Methods
/* private ArrayList PrepareSqlBuffers(string sql)
{
ArrayList buffers = new ArrayList();
MySqlStreamWriter writer = new MySqlStreamWriter(new MemoryStream(), connection.Encoding);
writer.Version = connection.driver.Version;
// if we are executing as a stored procedure, then we need to add the call
// keyword.
if (CommandType == CommandType.StoredProcedure)
{
if (storedProcedure == null)
storedProcedure = new StoredProcedure(this);
sql = storedProcedure.Prepare( CommandText );
}
// tokenize the SQL
sql = sql.TrimStart(';').TrimEnd(';');
ArrayList tokens = TokenizeSql( sql );
foreach (string token in tokens)
{
if (token.Trim().Length == 0) continue;
if (token == ";" && ! connection.driver.SupportsBatch)
{
MemoryStream ms = (MemoryStream)writer.Stream;
if (ms.Length > 0)
buffers.Add( ms );
writer = new MySqlStreamWriter(new MemoryStream(), connection.Encoding);
writer.Version = connection.driver.Version;
continue;
}
else if (token[0] == parameters.ParameterMarker)
{
if (SerializeParameter(writer, token)) continue;
}
// our fall through case is to write the token to the byte stream
writer.WriteStringNoNull(token);
}
// capture any buffer that is left over
MemoryStream mStream = (MemoryStream)writer.Stream;
if (mStream.Length > 0)
buffers.Add( mStream );
return buffers;
}*/
internal long EstimatedSize()
{
long size = CommandText.Length;
foreach (MySqlParameter parameter in Parameters)
size += parameter.EstimatedSize();
return size;
}
#endregion
#region ICloneable
/// <summary>
/// Creates a clone of this MySqlCommand object. CommandText, Connection, and Transaction properties
/// are included as well as the entire parameter list.
/// </summary>
/// <returns>The cloned MySqlCommand object</returns>
public MySqlCommand Clone()
{
MySqlCommand clone = new MySqlCommand(cmdText, connection, curTransaction);
clone.CommandType = CommandType;
clone.commandTimeout = commandTimeout;
clone.useDefaultTimeout = useDefaultTimeout;
clone.batchableCommandText = batchableCommandText;
clone.UpdatedRowSource = UpdatedRowSource;
clone.EnableCaching = EnableCaching;
clone.CacheAge = CacheAge;
foreach (MySqlParameter p in parameters)
{
clone.Parameters.Add(p.Clone());
}
return clone;
}
object ICloneable.Clone()
{
return this.Clone();
}
#endregion
#region Batching support
internal void AddToBatch(MySqlCommand command)
{
if (batch == null)
batch = new List<MySqlCommand>();
batch.Add(command);
}
internal string GetCommandTextForBatching()
{
if (batchableCommandText == null)
{
// if the command starts with insert and is "simple" enough, then
// we can use the multi-value form of insert
if (String.Compare(CommandText.Substring(0, 6), "INSERT", true) == 0)
{
MySqlCommand cmd = new MySqlCommand("SELECT @@sql_mode", Connection);
string sql_mode = cmd.ExecuteScalar().ToString().ToUpper(CultureInfo.InvariantCulture);
MySqlTokenizer tokenizer = new MySqlTokenizer(CommandText);
tokenizer.AnsiQuotes = sql_mode.IndexOf("ANSI_QUOTES") != -1;
tokenizer.BackslashEscapes = sql_mode.IndexOf("NO_BACKSLASH_ESCAPES") == -1;
string token = tokenizer.NextToken().ToLower(CultureInfo.InvariantCulture);
while (token != null)
{
if (token.ToUpper(CultureInfo.InvariantCulture) == "VALUES" &&
!tokenizer.Quoted)
{
token = tokenizer.NextToken();
Debug.Assert(token == "(");
// find matching right paren, and ensure that parens
// are balanced.
int openParenCount = 1;
while (token != null)
{
batchableCommandText += token;
token = tokenizer.NextToken();
if (token == "(")
openParenCount++;
else if (token == ")")
openParenCount--;
if (openParenCount == 0)
break;
}
if (token != null)
batchableCommandText += token;
token = tokenizer.NextToken();
if (token != null && (token == "," ||
token.ToUpper(CultureInfo.InvariantCulture) == "ON"))
{
batchableCommandText = null;
break;
}
}
token = tokenizer.NextToken();
}
}
// Otherwise use the command verbatim
else batchableCommandText = CommandText;
}
return batchableCommandText;
}
#endregion
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (statement != null && statement.IsPrepared)
statement.CloseStatement();
}
base.Dispose(disposing);
}
/// <summary>
/// Gets or sets a value indicating whether the command object should be visible in a Windows Form Designer control.
/// </summary>
#if !CF
[Browsable(false)]
#endif
public override bool DesignTimeVisible
{
get
{
return designTimeVisible;
}
set
{
designTimeVisible = value;
}
}
/// <summary>
/// Gets or sets how command results are applied to the DataRow when used by the
/// Update method of the DbDataAdapter.
/// </summary>
public override UpdateRowSource UpdatedRowSource
{
get
{
return updatedRowSource;
}
set
{
updatedRowSource = value;
}
}
protected override DbParameter CreateDbParameter()
{
return new MySqlParameter();
}
protected override DbConnection DbConnection
{
get { return Connection; }
set { Connection = (MySqlConnection)value; }
}
protected override DbParameterCollection DbParameterCollection
{
get { return Parameters; }
}
protected override DbTransaction DbTransaction
{
get { return Transaction; }
set { Transaction = (MySqlTransaction)value; }
}
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
return ExecuteReader(behavior);
}
}
}
|