2002-11-19 Tim Coleman <tim@timcoleman.com>
[mono.git] / mcs / class / Mono.Data.SybaseClient / Mono.Data.SybaseClient / SybaseCommand.cs
1 //
2 // Mono.Data.SybaseClient.SybaseCommand.cs
3 //
4 // Author:
5 //   Rodrigo Moya (rodrigo@ximian.com)
6 //   Daniel Morgan (danmorg@sc.rr.com)
7 //   Tim Coleman (tim@timcoleman.com)
8 //
9 // (C) Ximian, Inc 2002 http://www.ximian.com/
10 // (C) Daniel Morgan, 2002
11 // Copyright (C) Tim Coleman, 2002
12 //
13
14 using Mono.Data.TdsClient.Internal;
15 using System;
16 using System.Collections;
17 using System.Collections.Specialized;
18 using System.ComponentModel;
19 using System.Data;
20 using System.Data.Common;
21 using System.Runtime.InteropServices;
22 using System.Text;
23 using System.Xml;
24
25 namespace Mono.Data.SybaseClient {
26         public sealed class SybaseCommand : Component, IDbCommand, ICloneable
27         {
28                 #region Fields
29
30                 bool disposed = false;
31
32                 int commandTimeout;
33                 bool designTimeVisible;
34                 string commandText;
35
36                 CommandType commandType;
37                 SybaseConnection connection;
38                 SybaseTransaction transaction;
39                 UpdateRowSource updatedRowSource;
40
41                 CommandBehavior behavior = CommandBehavior.Default;
42                 NameValueCollection preparedStatements = new NameValueCollection ();
43                 SybaseParameterCollection parameters;
44
45                 #endregion // Fields
46
47                 #region Constructors
48
49                 public SybaseCommand() 
50                         : this (String.Empty, null, null)
51                 {
52                 }
53
54                 public SybaseCommand (string commandText) 
55                         : this (commandText, null, null)
56                 {
57                         commandText = commandText;
58                 }
59
60                 public SybaseCommand (string commandText, SybaseConnection connection) 
61                         : this (commandText, connection, null)
62                 {
63                         Connection = connection;
64                 }
65
66                 public SybaseCommand (string commandText, SybaseConnection connection, SybaseTransaction transaction) 
67                 {
68                         this.commandText = commandText;
69                         this.connection = connection;
70                         this.transaction = transaction;
71                         this.commandType = CommandType.Text;
72                         this.updatedRowSource = UpdateRowSource.Both;
73
74                         this.designTimeVisible = false;
75                         this.commandTimeout = 30;
76                         parameters = new SybaseParameterCollection (this);
77                 }
78
79                 #endregion // Constructors
80
81                 #region Properties
82
83                 internal CommandBehavior CommandBehavior {
84                         get { return behavior; }
85                 }
86
87                 public string CommandText {
88                         get { return commandText; }
89                         set { commandText = value; }
90                 }
91
92                 public int CommandTimeout {
93                         get { return commandTimeout;  }
94                         set { 
95                                 if (commandTimeout < 0)
96                                         throw new ArgumentException ("The property value assigned is less than 0.");
97                                 commandTimeout = value; 
98                         }
99                 }
100
101                 public CommandType CommandType  {
102                         get { return commandType; }
103                         set { 
104                                 if (value == CommandType.TableDirect)
105                                         throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SybaseClient Data Provider.");
106                                 commandType = value; 
107                         }
108                 }
109
110                 public SybaseConnection Connection {
111                         get { return connection; }
112                         set { 
113                                 if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
114                                         throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
115                                 transaction = null;
116                                 connection = value; 
117                         }
118                 }
119
120                 public bool DesignTimeVisible {
121                         get { return designTimeVisible; } 
122                         set { designTimeVisible = value; }
123                 }
124
125                 public SybaseParameterCollection Parameters {
126                         get { return parameters; }
127                 }
128
129                 internal ITds Tds {
130                         get { return Connection.Tds; }
131                 }
132
133                 IDbConnection IDbCommand.Connection {
134                         get { return Connection; }
135                         set { 
136                                 if (!(value is SybaseConnection))
137                                         throw new InvalidCastException ("The value was not a valid SybaseConnection.");
138                                 Connection = (SybaseConnection) value;
139                         }
140                 }
141
142                 IDataParameterCollection IDbCommand.Parameters  {
143                         get { return Parameters; }
144                 }
145
146                 IDbTransaction IDbCommand.Transaction {
147                         get { return Transaction; }
148                         set { 
149                                 if (!(value is SybaseTransaction))
150                                         throw new ArgumentException ();
151                                 Transaction = (SybaseTransaction) value; 
152                         }
153                 }
154
155                 public SybaseTransaction Transaction {
156                         get { return transaction; }
157                         set { transaction = value; }
158                 }       
159
160                 public UpdateRowSource UpdatedRowSource {
161                         get { return updatedRowSource; }
162                         set { updatedRowSource = value; }
163                 }
164
165                 #endregion // Fields
166
167                 #region Methods
168
169                 private string BuildCommand ()
170                 {
171                         string statementHandle = preparedStatements [commandText];
172                         if (statementHandle != null) {
173                                 string proc = String.Format ("sp_execute {0}", statementHandle);        
174                                 if (parameters.Count > 0)
175                                         proc += ",";
176                                 return BuildProcedureCall (proc, parameters);
177                         }
178
179                         if (commandType == CommandType.StoredProcedure)
180                                 return BuildProcedureCall (commandText, parameters);
181
182                         string sql = String.Empty;
183                         if ((behavior & CommandBehavior.KeyInfo) > 0)
184                                 sql += "SET FMTONLY OFF; SET NO_BROWSETABLE ON;";
185                         if ((behavior & CommandBehavior.SchemaOnly) > 0)
186                                 sql += "SET FMTONLY ON;";
187         
188                         switch (commandType) {
189                         case CommandType.Text :
190                                 sql += commandText;
191                                 break;
192                         default:
193                                 throw new InvalidOperationException ("The CommandType was invalid.");
194                         }
195                         return BuildExec (sql);
196                 }
197
198                 [MonoTODO ("This throws a SybaseException.")]
199                 private string BuildExec (string sql)
200                 {
201                         StringBuilder declare = new StringBuilder ();
202                         StringBuilder assign = new StringBuilder ();
203
204                         sql = sql.Replace ("'", "''");
205                         foreach (SybaseParameter parameter in parameters) {
206                                 declare.Append ("declare ");
207                                 declare.Append (parameter.Prepare (parameter.ParameterName));
208                                 if (parameter.Direction == ParameterDirection.Output)
209                                         declare.Append (" output");
210                                 declare.Append ('\n');
211                                 assign.Append (String.Format ("select {0}={1}\n", parameter.ParameterName, FormatParameter (parameter)));
212                         }
213
214                         return String.Format ("{0}{1}{2}", declare.ToString (), assign.ToString (), sql);
215                 }
216
217                 private string BuildPrepare ()
218                 {
219                         StringBuilder parms = new StringBuilder ();
220                         foreach (SybaseParameter parameter in parameters) {
221                                 if (parms.Length > 0)
222                                         parms.Append (", ");
223                                 parms.Append (parameter.Prepare (parameter.ParameterName));
224                                 if (parameter.Direction == ParameterDirection.Output)
225                                         parms.Append (" output");
226                         }
227
228                         SybaseParameterCollection localParameters = new SybaseParameterCollection (this);
229                         SybaseParameter parm;
230                 
231                         parm = new SybaseParameter ("@P1", SybaseType.Int);
232                         parm.Direction = ParameterDirection.Output;
233                         localParameters.Add (parm);
234
235                         parm = new SybaseParameter ("@P2", SybaseType.NVarChar);
236                         parm.Value = parms.ToString ();
237                         parm.Size = ((string) parm.Value).Length;
238                         localParameters.Add (parm);
239
240                         parm = new SybaseParameter ("@P3", SybaseType.NVarChar);
241                         parm.Value = commandText;
242                         parm.Size = ((string) parm.Value).Length;
243                         localParameters.Add (parm);
244
245                         return BuildProcedureCall ("sp_prepare", localParameters);
246                 }
247
248                 private static string BuildProcedureCall (string procedure, SybaseParameterCollection parameters)
249                 {
250                         StringBuilder parms = new StringBuilder ();
251                         StringBuilder declarations = new StringBuilder ();
252                         StringBuilder outParms = new StringBuilder ();
253                         StringBuilder set = new StringBuilder ();
254
255                         int index = 1;
256                         foreach (SybaseParameter parameter in parameters) {
257                                 string parmName = String.Format ("@P{0}", index);
258
259                                 switch (parameter.Direction) {
260                                 case ParameterDirection.Input :
261                                         if (parms.Length > 0)
262                                                 parms.Append (", ");
263                                         parms.Append (FormatParameter (parameter));
264                                         break;
265                                 case ParameterDirection.Output :
266                                         if (parms.Length > 0)
267                                                 parms.Append (", ");
268                                         parms.Append (parmName);
269                                         parms.Append (" output");
270
271                                         if (outParms.Length > 0) {
272                                                 outParms.Append (", ");
273                                                 declarations.Append (", ");
274                                         }
275                                         else {
276                                                 outParms.Append ("select ");
277                                                 declarations.Append ("declare ");
278                                         }
279
280                                         declarations.Append (parameter.Prepare (parmName));
281                                         set.Append (String.Format ("set {0}=NULL\n", parmName));
282                                         outParms.Append (parmName);
283                                         break;
284                                 default :
285                                         throw new NotImplementedException ("Only support input and output parameters.");
286                                 }
287                                 index += 1;
288                         }
289                         if (declarations.Length > 0)
290                                 declarations.Append ('\n');
291
292                         return String.Format ("{0}{1}{2} {3}\n{4}", declarations.ToString (), set.ToString (), procedure, parms.ToString (), outParms.ToString ());
293                 }
294
295                 public void Cancel () 
296                 {
297                         if (Connection == null || Connection.Tds == null)
298                                 return;
299                         Connection.Tds.Cancel ();
300                 }
301
302                 internal void CloseDataReader (bool moreResults)
303                 {
304                         GetOutputParameters ();
305                         Connection.DataReader = null;
306
307                         if ((behavior & CommandBehavior.CloseConnection) != 0)
308                                 Connection.Close ();
309                 }
310
311                 public SybaseParameter CreateParameter () 
312                 {
313                         return new SybaseParameter ();
314                 }
315
316                 internal void DeriveParameters ()
317                 {
318                         if (commandType != CommandType.StoredProcedure)
319                                 throw new InvalidOperationException (String.Format ("SybaseCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
320                         ValidateCommand ("DeriveParameters");
321
322                         SybaseParameterCollection localParameters = new SybaseParameterCollection (this);
323                         localParameters.Add ("@P1", SybaseType.NVarChar, commandText.Length).Value = commandText;
324
325                         Connection.Tds.ExecuteQuery (BuildProcedureCall ("sp_procedure_params_rowset", localParameters));
326                         SybaseDataReader reader = new SybaseDataReader (this);
327                         parameters.Clear ();
328                         object[] dbValues = new object[reader.FieldCount];
329
330                         while (reader.Read ()) {
331                                 reader.GetValues (dbValues);
332                                 parameters.Add (new SybaseParameter (dbValues));
333                         }
334                         reader.Close ();        
335                 }
336
337                 public int ExecuteNonQuery ()
338                 {
339                         ValidateCommand ("ExecuteNonQuery");
340                         string sql = String.Empty;
341                         int result = 0;
342
343                         if (Parameters.Count > 0)
344                                 sql = BuildCommand ();
345                         else
346                                 sql = CommandText;
347
348                         try {
349                                 result = Connection.Tds.ExecuteNonQuery (sql, CommandTimeout);
350                         }
351                         catch (TdsTimeoutException e) {
352                                 throw SybaseException.FromTdsInternalException ((TdsInternalException) e);
353                         }
354
355                         GetOutputParameters ();
356                         return result;
357                 }
358
359                 public SybaseDataReader ExecuteReader ()
360                 {
361                         return ExecuteReader (CommandBehavior.Default);
362                 }
363
364                 public SybaseDataReader ExecuteReader (CommandBehavior behavior)
365                 {
366                         ValidateCommand ("ExecuteReader");
367                         this.behavior = behavior;
368
369                         try {
370                                 Connection.Tds.ExecuteQuery (BuildCommand (), CommandTimeout);
371                         }
372                         catch (TdsTimeoutException e) {
373                                 throw SybaseException.FromTdsInternalException ((TdsInternalException) e);
374                         }
375                 
376                         Connection.DataReader = new SybaseDataReader (this);
377                         return Connection.DataReader;
378                 }
379
380                 public object ExecuteScalar ()
381                 {
382                         ValidateCommand ("ExecuteScalar");
383                         try {
384                                 Connection.Tds.ExecuteQuery (BuildCommand (), CommandTimeout);
385                         }
386                         catch (TdsTimeoutException e) {
387                                 throw SybaseException.FromTdsInternalException ((TdsInternalException) e);
388                         }
389
390                         if (!Connection.Tds.NextResult () || !Connection.Tds.NextRow ())
391                                 return null;
392
393                         object result = Connection.Tds.ColumnValues [0];
394                         CloseDataReader (true);
395                         return result;
396                 }
397
398                 [MonoTODO ("Include offset from SybaseParameter for binary/string types.")]
399                 static string FormatParameter (SybaseParameter parameter)
400                 {
401                         if (parameter.Value == null)
402                                 return "NULL";
403
404                         switch (parameter.SybaseType) {
405                                 case SybaseType.BigInt :
406                                 case SybaseType.Decimal :
407                                 case SybaseType.Float :
408                                 case SybaseType.Int :
409                                 case SybaseType.Money :
410                                 case SybaseType.Real :
411                                 case SybaseType.SmallInt :
412                                 case SybaseType.SmallMoney :
413                                 case SybaseType.TinyInt :
414                                         return parameter.Value.ToString ();
415                                 case SybaseType.NVarChar :
416                                 case SybaseType.NChar :
417                                         return String.Format ("N'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
418                                 case SybaseType.UniqueIdentifier :
419                                         return String.Format ("0x{0}", ((Guid) parameter.Value).ToString ("N"));
420                                 case SybaseType.Bit:
421                                         if (parameter.Value.GetType () == typeof (bool))
422                                                 return (((bool) parameter.Value) ? "0x1" : "0x0");
423                                         return parameter.Value.ToString ();
424                                 case SybaseType.Image:
425                                 case SybaseType.Binary:
426                                 case SybaseType.VarBinary:
427                                         return String.Format ("0x{0}", BitConverter.ToString ((byte[]) parameter.Value).Replace ("-", "").ToLower ());
428                                 default:
429                                         return String.Format ("'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
430                         }
431                 }
432
433                 private void GetOutputParameters ()
434                 {
435                         Connection.Tds.SkipToEnd ();
436
437                         IList list = Connection.Tds.ColumnValues;
438
439                         if (list != null && list.Count > 0) {
440                                 int index = 0;
441                                 foreach (SybaseParameter parameter in parameters) {
442                                         if (parameter.Direction != ParameterDirection.Input) {
443                                                 parameter.Value = list [index];
444                                                 index += 1;
445                                         }
446                                         if (index >= list.Count)
447                                                 break;
448                                 }
449                         }
450                 }
451
452                 object ICloneable.Clone ()
453                 {
454                         return new SybaseCommand (commandText, Connection);
455                 }
456
457                 IDbDataParameter IDbCommand.CreateParameter ()
458                 {
459                         return CreateParameter ();
460                 }
461
462                 IDataReader IDbCommand.ExecuteReader ()
463                 {
464                         return ExecuteReader ();
465                 }
466
467                 IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
468                 {
469                         return ExecuteReader (behavior);
470                 }
471
472                 public void Prepare ()
473                 {
474                         ValidateCommand ("Prepare");
475                         Connection.Tds.ExecuteNonQuery (BuildPrepare ());
476
477                         if (Connection.Tds.OutputParameters.Count == 0 || Connection.Tds.OutputParameters[0] == null)
478                                 throw new Exception ("Could not prepare the statement.");
479
480                         preparedStatements [commandText] = ((int) Connection.Tds.OutputParameters [0]).ToString ();
481                 }
482
483                 public void ResetCommandTimeout ()
484                 {
485                         commandTimeout = 30;
486                 }
487
488                 private void ValidateCommand (string method)
489                 {
490                         if (Connection == null)
491                                 throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
492                         if (Connection.Transaction != null && transaction != Connection.Transaction)
493                                 throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
494                         if (Connection.State != ConnectionState.Open)
495                                 throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
496                         if (commandText == String.Empty || commandText == null)
497                                 throw new InvalidOperationException ("The command text for this Command has not been set.");
498                         if (Connection.DataReader != null)
499                                 throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
500                 }
501
502                 #endregion // Methods
503         }
504 }