2002-05-26 Daniel Morgan <danmorg@sc.rr.com>
authorDaniel Morgan <monodanmorg@yahoo.com>
Sun, 26 May 2002 07:26:52 +0000 (07:26 -0000)
committerDaniel Morgan <monodanmorg@yahoo.com>
Sun, 26 May 2002 07:26:52 +0000 (07:26 -0000)
* Test/SqlSharpCli.cs: added file
My new toy.  SQL# is a command-line tool to enter
SQL commands and queries using Mono System.Data.
It also serves as a test for Mono System.Data.

* System.Data.SqlClient/SqlCommand.cs: modified
- ExecuteNonQuery(), ExecuteScalar(), and ExecuteReader()
should handle the results from SQL Commands and Queries.
- Internal class SqlResult should not create schema Table
for the result from a SQL Command.  Also, set the RecordsRetrieved
property for SqlDataReader.
- Closing the SqlDataReader should Close() the SqlConnection for
a CommandBehavior.CloseConnection.
- Set defaults for SqlResult

* System.Data.SqlClient/SqlConnection.cs: modified -
when SqlDataReader is Close()
should Close() the SqlConnection for
a CommandBehavior.CloseConnection.  Changed internal Property
from OpenReader get/set to IsReaderOpen get and created
internal methods OpenReader()/CloseReader() for SqlCommand to call.
SqlConnection needs to be prevented from doing while SqlDataReader
is being used.

* System.Data.SqlClient/SqlDataReader.cs: modified -
call SqlCommand's OpenReader() internal method.  get
RecordsRetrieved from SqlResult.  set/reset default
values for SqlDataReader.

* Test/PostgresTest.cs
* Test/TestExecuteScalar.cs
* Test/TestSqlDataReader.cs: modified
for the Execute...() methods in SqlCommand
to test SQL Queries and Commands

* Test/System.Data_test.build: modified
exclude new file Test/SqlSharpCli.cs from
test build

svn path=/trunk/mcs/; revision=4944

16 files changed:
mcs/class/Mono.Data.PostgreSqlClient/Mono.Data.PostgreSqlClient/PgSqlCommand.cs
mcs/class/Mono.Data.PostgreSqlClient/Mono.Data.PostgreSqlClient/PgSqlConnection.cs
mcs/class/Mono.Data.PostgreSqlClient/Mono.Data.PostgreSqlClient/PgSqlDataReader.cs
mcs/class/Mono.Data.PostgreSqlClient/PgSqlCommand.cs
mcs/class/Mono.Data.PostgreSqlClient/PgSqlConnection.cs
mcs/class/Mono.Data.PostgreSqlClient/PgSqlDataReader.cs
mcs/class/System.Data/ChangeLog
mcs/class/System.Data/System.Data.SqlClient/SqlCommand.cs
mcs/class/System.Data/System.Data.SqlClient/SqlConnection.cs
mcs/class/System.Data/System.Data.SqlClient/SqlDataReader.cs
mcs/class/System.Data/Test/PostgresTest.cs
mcs/class/System.Data/Test/SqlSharpCli.cs [new file with mode: 0644]
mcs/class/System.Data/Test/System.Data_test.build
mcs/class/System.Data/Test/TestExecuteScalar.cs
mcs/class/System.Data/Test/TestSqlDataReader.cs
mcs/tools/SqlSharp/SqlSharpCli.cs [new file with mode: 0644]

index f9064516c02d722097e456c435105bb40aa50e14..1d4c8c5bc9ca3b2c5c44694ce16da3230655d7d0 100644 (file)
@@ -135,7 +135,9 @@ namespace System.Data.SqlClient {
                        execStatus = PostgresLibrary.
                                PQresultStatus (pgResult);
                        
-                       if(execStatus == ExecStatusType.PGRES_COMMAND_OK) {
+                       if(execStatus == ExecStatusType.PGRES_COMMAND_OK ||
+                               execStatus == ExecStatusType.PGRES_TUPLES_OK ) {
+
                                rowsAffectedString = PostgresLibrary.
                                        PQcmdTuples (pgResult);
 
@@ -317,7 +319,11 @@ namespace System.Data.SqlClient {
                        execStatus = PostgresLibrary.
                                PQresultStatus (pgResult);
                        
-                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
+                       res.ExecStatus = execStatus;
+
+                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK ||
+                               execStatus == ExecStatusType.PGRES_COMMAND_OK) {
+
                                res.BuildTableSchema(pgResult);
                        }
                        else {
@@ -343,9 +349,21 @@ namespace System.Data.SqlClient {
                // those resources.  Also, need to allow this SqlCommand
                // and this SqlConnection to do things again.
                internal void CloseReader() {
-                       conn.OpenReader = false;
                        dataReader = null;
                        queries = null;
+
+                       if((cmdBehavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection) {
+                               conn.CloseReader(true);
+                       }
+                       else {
+                               conn.CloseReader(false);
+                       }
+               }
+
+               // only meant to be used between SqlConnectioin,
+               // SqlCommand, and SqlDataReader
+               internal void OpenReader(SqlDataReader reader) {
+                       conn.OpenReader(reader);
                }
 
                /// <summary>\r
@@ -385,8 +403,18 @@ namespace System.Data.SqlClient {
 
                        execStatus = PostgresLibrary.
                                PQresultStatus (pgResult);
-                       
-                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
+                       if(execStatus == ExecStatusType.PGRES_COMMAND_OK) {
+                               // result was a SQL Command 
+
+                               // close result set
+                               PostgresLibrary.PQclear (pgResult);
+                               pgResult = IntPtr.Zero;
+
+                               return null; // return null reference
+                       }
+                       else if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
+                               // result was a SQL Query
+
                                nRows = PostgresLibrary.
                                        PQntuples(pgResult);
 
@@ -648,13 +676,24 @@ namespace System.Data.SqlClient {
        // from SqlCommand to SqlDataReader
        internal class SqlResult {
 
-               private DataTable dataTableSchema; // only will contain the schema
-               private IntPtr pg_result; // native PostgreSQL PGresult
-               private int rowCount; 
-               private int fieldCount;
-               private string[] pgtypes; // PostgreSQL types (typname)
+               private DataTable dataTableSchema = null; // only will contain the schema
+               private IntPtr pg_result = IntPtr.Zero; // native PostgreSQL PGresult
+               private int rowCount = 0
+               private int fieldCount = 0;
+               private string[] pgtypes = null; // PostgreSQL types (typname)
                private bool resultReturned = false;
-               private SqlConnection con;
+               private SqlConnection con = null;
+               private int rowsAffected = -1;
+               private ExecStatusType execStatus = ExecStatusType.PGRES_FATAL_ERROR;
+
+               internal ExecStatusType ExecStatus {
+                       get {
+                               return execStatus;
+                       }
+                       set {
+                               execStatus = value;
+                       }
+               }
 
                internal SqlConnection Connection {
                        set {
@@ -662,6 +701,12 @@ namespace System.Data.SqlClient {
                        }
                }
 
+               internal int RecordsAffected {
+                       get {
+                               return rowsAffected;
+                       }
+               }
+
                internal bool ResultReturned {
                        get {
                                return resultReturned;
@@ -701,93 +746,104 @@ namespace System.Data.SqlClient {
                        }
                }
 
-               internal void BuildTableSchema (IntPtr pgResult) 
-               {
+               internal void BuildTableSchema (IntPtr pgResult) {
                        pg_result = pgResult;
+                       
+                       // need to set IDataReader.RecordsAffected property
+                       string rowsAffectedString;
+                       rowsAffectedString = PostgresLibrary.
+                               PQcmdTuples (pgResult);
+                       if(rowsAffectedString != null)
+                               if(rowsAffectedString.Equals("") == false)
+                                       rowsAffected = int.Parse(rowsAffectedString);
+                       
+                       // Only Results from SQL SELECT Queries 
+                       // get a DataTable for schema of the result
+                       // otherwise, DataTable is null reference
+                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
 
-                       dataTableSchema = new DataTable ();
-                       dataTableSchema.Columns.Add ("ColumnName", typeof (string));
-                       dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
-                       dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
-                       dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
-                       dataTableSchema.Columns.Add ("NumericScale", typeof (int));
-                       dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsKey", typeof (bool));
-                       dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
-                       dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
-                       dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
-                       dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
-                       dataTableSchema.Columns.Add ("DataType", typeof(string));
-                       dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
-                       dataTableSchema.Columns.Add ("ProviderType", typeof (int));
-                       dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsLong", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
-
-                       fieldCount = PostgresLibrary.PQnfields (pgResult);
-                       rowCount = PostgresLibrary.PQntuples(pgResult);
-                       pgtypes = new string[fieldCount];\r
-
-                       DataRow schemaRow;
-                       int oid;
-                       DbType dbType;
-                       Type typ;
+                               dataTableSchema = new DataTable ();
+                               dataTableSchema.Columns.Add ("ColumnName", typeof (string));
+                               dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
+                               dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
+                               dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
+                               dataTableSchema.Columns.Add ("NumericScale", typeof (int));
+                               dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsKey", typeof (bool));
+                               dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
+                               dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
+                               dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
+                               dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
+                               dataTableSchema.Columns.Add ("DataType", typeof(string));
+                               dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
+                               dataTableSchema.Columns.Add ("ProviderType", typeof (int));
+                               dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsLong", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
+
+                               fieldCount = PostgresLibrary.PQnfields (pgResult);
+                               rowCount = PostgresLibrary.PQntuples(pgResult);
+                               pgtypes = new string[fieldCount];\r
+
+                               DataRow schemaRow;
+                               int oid;
+                               DbType dbType;
+                               Type typ;
                                                
-                       for (int i = 0; i < fieldCount; i += 1 )
-                       {
-                               schemaRow = dataTableSchema.NewRow ();
-
-                               schemaRow["ColumnName"] = PostgresLibrary.PQfname (pgResult, i);
-                               schemaRow["ColumnOrdinal"] = i+1;
-                               schemaRow["ColumnSize"] = PostgresLibrary.PQfsize (pgResult, i);
-                               schemaRow["NumericPrecision"] = 0; // ? tim
-                               schemaRow["NumericScale"] = 0; // ? tim
-                               schemaRow["IsUnique"] = false; // ? tim
-                               schemaRow["IsKey"] = false; // ? tim
-                               schemaRow["BaseCatalogName"] = ""; // ? tim
-                               schemaRow["BaseColumnName"] = PostgresLibrary.PQfname (pgResult, i);
-                               schemaRow["BaseSchemaName"] = ""; // ? tim
-                               schemaRow["BaseTableName"]  = ""; // ? tim
+                               for (int i = 0; i < fieldCount; i += 1 ) {
+                                       schemaRow = dataTableSchema.NewRow ();
+
+                                       schemaRow["ColumnName"] = PostgresLibrary.PQfname (pgResult, i);
+                                       schemaRow["ColumnOrdinal"] = i+1;
+                                       schemaRow["ColumnSize"] = PostgresLibrary.PQfsize (pgResult, i);
+                                       schemaRow["NumericPrecision"] = 0;
+                                       schemaRow["NumericScale"] = 0;
+                                       schemaRow["IsUnique"] = false;
+                                       schemaRow["IsKey"] = false;
+                                       schemaRow["BaseCatalogName"] = "";
+                                       schemaRow["BaseColumnName"] = PostgresLibrary.PQfname (pgResult, i);
+                                       schemaRow["BaseSchemaName"] = "";
+                                       schemaRow["BaseTableName"]  = "";
                                
-                               // PostgreSQL type to .NET type stuff
-                               oid = PostgresLibrary.PQftype (pgResult, i);
-                               pgtypes[i] = PostgresHelper.OidToTypname (oid, con.Types);      \r
-                               dbType = PostgresHelper.TypnameToSqlDbType (pgtypes[i]);\r
+                                       // PostgreSQL type to .NET type stuff
+                                       oid = PostgresLibrary.PQftype (pgResult, i);
+                                       pgtypes[i] = PostgresHelper.OidToTypname (oid, con.Types);      \r
+                                       dbType = PostgresHelper.TypnameToSqlDbType (pgtypes[i]);\r
                                \r
-                               typ = PostgresHelper.DbTypeToSystemType (dbType);\r
-                               string st = typ.ToString();\r
-                               schemaRow["DataType"] = st;\r
-
-                               schemaRow["AllowDBNull"] = false; // ? tim
-                               schemaRow["ProviderType"] = oid; // ? tim
-                               schemaRow["IsAliased"] = false; // ? tim
-                               schemaRow["IsExpression"] = false; // ? tim
-                               schemaRow["IsIdentity"] = false; // ? tim
-                               schemaRow["IsAutoIncrement"] = false; // ? tim
-                               schemaRow["IsRowVersion"] = false; // ? tim
-                               schemaRow["IsHidden"] = false; // ? tim
-                               schemaRow["IsLong"] = false; // ? tim
-                               schemaRow["IsReadOnly"] = false; // ? tim
-                               schemaRow.AcceptChanges();
-                               dataTableSchema.Rows.Add (schemaRow);
-                               
-                       }
+                                       typ = PostgresHelper.DbTypeToSystemType (dbType);\r
+                                       string st = typ.ToString();\r
+                                       schemaRow["DataType"] = st;\r
+
+                                       schemaRow["AllowDBNull"] = false;
+                                       schemaRow["ProviderType"] = oid;
+                                       schemaRow["IsAliased"] = false;
+                                       schemaRow["IsExpression"] = false;
+                                       schemaRow["IsIdentity"] = false;
+                                       schemaRow["IsAutoIncrement"] = false;
+                                       schemaRow["IsRowVersion"] = false;
+                                       schemaRow["IsHidden"] = false;
+                                       schemaRow["IsLong"] = false;
+                                       schemaRow["IsReadOnly"] = false;
+                                       schemaRow.AcceptChanges();
+                                       dataTableSchema.Rows.Add (schemaRow);   
+                               }
 
 #if DEBUG_SqlCommand
-                       Console.WriteLine("********** DEBUG Table Schema BEGIN ************");
-                       foreach (DataRow myRow in dataTableSchema.Rows) {\r
-                               foreach (DataColumn myCol in dataTableSchema.Columns)\r
-                                       Console.WriteLine(myCol.ColumnName + " = " + myRow[myCol]);\r
-                               Console.WriteLine();\r
-                       }
-                       Console.WriteLine("********** DEBUG Table Schema END ************");
+                               Console.WriteLine("********** DEBUG Table Schema BEGIN ************");
+                               foreach (DataRow myRow in dataTableSchema.Rows) {\r
+                                       foreach (DataColumn myCol in dataTableSchema.Columns)\r
+                                               Console.WriteLine(myCol.ColumnName + " = " + myRow[myCol]);\r
+                                       Console.WriteLine();\r
+                               }
+                               Console.WriteLine("********** DEBUG Table Schema END ************");
 #endif // DEBUG_SqlCommand
 
+                       }
                }
        }
 }
index 785fca0669ed04ea555747f9af99541052592251..26a047868426c5e730b96e0eb7d94b93d733c13f 100644 (file)
@@ -45,8 +45,9 @@ namespace System.Data.SqlClient {
 
                #region Fields
 
-               private PostgresTypes types;
+               private PostgresTypes types = null;
                private IntPtr pgConn = IntPtr.Zero;    
+
                // PGConn (Postgres Connection)
                private string connectionString = "";    
                // OLE DB Connection String
@@ -82,7 +83,11 @@ namespace System.Data.SqlClient {
                // support SSL. Set to 0 (default) to 
                // negotiate with server. 
 
+               // connection state
                private ConnectionState conState = ConnectionState.Closed;
+               
+               // DataReader state
+               private SqlDataReader rdr = null;
                private bool dataReaderOpen = false;
                // FIXME: if true, throw an exception if SqlConnection 
                //        is used for anything other than reading
@@ -167,6 +172,12 @@ namespace System.Data.SqlClient {
                                
                [MonoTODO]
                public void Close () {
+                       if(dataReaderOpen == true) {
+                               // TODO: what do I do if
+                               // the user Closes the connection
+                               // without closing the Reader first?
+
+                       }                       
                        CloseDataSource ();
                }
 
@@ -235,6 +246,40 @@ namespace System.Data.SqlClient {
 
                #endregion
 
+               #region Internal Methods
+
+               // Used to prevent SqlConnection
+               // from doing anything while
+               // SqlDataReader is open.
+               // Open the Reader. (called from SqlCommand)
+               internal void OpenReader(SqlDataReader reader) 
+               {       
+                       if(dataReaderOpen == true) {
+                               // TODO: throw exception here?
+                               //       because a reader
+                               //       is already open
+                       }
+                       else {
+                               rdr = reader;
+                               dataReaderOpen = true;
+                       }
+               }
+
+               // Used to prevent SqlConnection
+               // from doing anything while
+               // SqlDataReader is open
+               // Close the Reader (called from SqlCommand)
+               // if closeConnection true, Close() the connection
+               // this is based on CommandBehavior.CloseConnection
+               internal void CloseReader(bool closeConnection)
+               {       if(closeConnection == true)
+                               CloseDataSource();
+                       else
+                               dataReaderOpen = false;
+               }
+
+               #endregion // Internal Methods
+
                #region Private Methods
 
                private void SetupConnection() {
@@ -261,9 +306,11 @@ namespace System.Data.SqlClient {
 
                private void CloseDataSource () {
                        // FIXME: just a quick hack
-                       conState = ConnectionState.Closed;
-                       PostgresLibrary.PQfinish (pgConn);
-                       pgConn = IntPtr.Zero;
+                       if(conState == ConnectionState.Open) {
+                               conState = ConnectionState.Closed;
+                               PostgresLibrary.PQfinish (pgConn);
+                               pgConn = IntPtr.Zero;
+                       }
                }
 
                private void SetConnectionString (string connectionString) {
@@ -515,13 +562,10 @@ namespace System.Data.SqlClient {
                // Used to prevent SqlConnection
                // from doing anything while
                // SqlDataReader is open
-               internal bool OpenReader {
+               internal bool IsReaderOpen {
                        get {
                                return dataReaderOpen;
                        }
-                       set {
-                               dataReaderOpen = value;
-                       }
                }
 
                #endregion // Internal Properties
index 6d55d61673a820f32770d4c089b88670181b21ab..28d0e1bc4e725012ab50bcbd4a281d4adef64e9a 100644 (file)
@@ -68,6 +68,7 @@ namespace System.Data.SqlClient {
 
                        cmd = sqlCmd;
                        open = true;
+                       cmd.OpenReader(this);
                }
 
                #endregion
@@ -98,18 +99,30 @@ namespace System.Data.SqlClient {
                public bool NextResult() {
                        SqlResult res;
                        currentRow = -1;
+                       bool resultReturned;
                        
+                       // reset
+                       table = null;
+                       pgResult = IntPtr.Zero;
+                       rows = 0;
+                       cols = 0;
+                       types = null;
+                       recordsAffected = -1;
+
                        res = cmd.NextResult();
+                       resultReturned = res.ResultReturned;
 
-                       if(res.ResultReturned == true) {
+                       if(resultReturned == true) {
                                table = res.Table;
                                pgResult = res.PgResult;
                                rows = res.RowCount;
                                cols = res.FieldCount;
                                types = res.PgTypes;
+                               recordsAffected = res.RecordsAffected;
                        }
-
-                       return res.ResultReturned;
+                       
+                       res = null;
+                       return resultReturned;
                }
 
                [MonoTODO]
index f9064516c02d722097e456c435105bb40aa50e14..1d4c8c5bc9ca3b2c5c44694ce16da3230655d7d0 100644 (file)
@@ -135,7 +135,9 @@ namespace System.Data.SqlClient {
                        execStatus = PostgresLibrary.
                                PQresultStatus (pgResult);
                        
-                       if(execStatus == ExecStatusType.PGRES_COMMAND_OK) {
+                       if(execStatus == ExecStatusType.PGRES_COMMAND_OK ||
+                               execStatus == ExecStatusType.PGRES_TUPLES_OK ) {
+
                                rowsAffectedString = PostgresLibrary.
                                        PQcmdTuples (pgResult);
 
@@ -317,7 +319,11 @@ namespace System.Data.SqlClient {
                        execStatus = PostgresLibrary.
                                PQresultStatus (pgResult);
                        
-                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
+                       res.ExecStatus = execStatus;
+
+                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK ||
+                               execStatus == ExecStatusType.PGRES_COMMAND_OK) {
+
                                res.BuildTableSchema(pgResult);
                        }
                        else {
@@ -343,9 +349,21 @@ namespace System.Data.SqlClient {
                // those resources.  Also, need to allow this SqlCommand
                // and this SqlConnection to do things again.
                internal void CloseReader() {
-                       conn.OpenReader = false;
                        dataReader = null;
                        queries = null;
+
+                       if((cmdBehavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection) {
+                               conn.CloseReader(true);
+                       }
+                       else {
+                               conn.CloseReader(false);
+                       }
+               }
+
+               // only meant to be used between SqlConnectioin,
+               // SqlCommand, and SqlDataReader
+               internal void OpenReader(SqlDataReader reader) {
+                       conn.OpenReader(reader);
                }
 
                /// <summary>\r
@@ -385,8 +403,18 @@ namespace System.Data.SqlClient {
 
                        execStatus = PostgresLibrary.
                                PQresultStatus (pgResult);
-                       
-                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
+                       if(execStatus == ExecStatusType.PGRES_COMMAND_OK) {
+                               // result was a SQL Command 
+
+                               // close result set
+                               PostgresLibrary.PQclear (pgResult);
+                               pgResult = IntPtr.Zero;
+
+                               return null; // return null reference
+                       }
+                       else if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
+                               // result was a SQL Query
+
                                nRows = PostgresLibrary.
                                        PQntuples(pgResult);
 
@@ -648,13 +676,24 @@ namespace System.Data.SqlClient {
        // from SqlCommand to SqlDataReader
        internal class SqlResult {
 
-               private DataTable dataTableSchema; // only will contain the schema
-               private IntPtr pg_result; // native PostgreSQL PGresult
-               private int rowCount; 
-               private int fieldCount;
-               private string[] pgtypes; // PostgreSQL types (typname)
+               private DataTable dataTableSchema = null; // only will contain the schema
+               private IntPtr pg_result = IntPtr.Zero; // native PostgreSQL PGresult
+               private int rowCount = 0
+               private int fieldCount = 0;
+               private string[] pgtypes = null; // PostgreSQL types (typname)
                private bool resultReturned = false;
-               private SqlConnection con;
+               private SqlConnection con = null;
+               private int rowsAffected = -1;
+               private ExecStatusType execStatus = ExecStatusType.PGRES_FATAL_ERROR;
+
+               internal ExecStatusType ExecStatus {
+                       get {
+                               return execStatus;
+                       }
+                       set {
+                               execStatus = value;
+                       }
+               }
 
                internal SqlConnection Connection {
                        set {
@@ -662,6 +701,12 @@ namespace System.Data.SqlClient {
                        }
                }
 
+               internal int RecordsAffected {
+                       get {
+                               return rowsAffected;
+                       }
+               }
+
                internal bool ResultReturned {
                        get {
                                return resultReturned;
@@ -701,93 +746,104 @@ namespace System.Data.SqlClient {
                        }
                }
 
-               internal void BuildTableSchema (IntPtr pgResult) 
-               {
+               internal void BuildTableSchema (IntPtr pgResult) {
                        pg_result = pgResult;
+                       
+                       // need to set IDataReader.RecordsAffected property
+                       string rowsAffectedString;
+                       rowsAffectedString = PostgresLibrary.
+                               PQcmdTuples (pgResult);
+                       if(rowsAffectedString != null)
+                               if(rowsAffectedString.Equals("") == false)
+                                       rowsAffected = int.Parse(rowsAffectedString);
+                       
+                       // Only Results from SQL SELECT Queries 
+                       // get a DataTable for schema of the result
+                       // otherwise, DataTable is null reference
+                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
 
-                       dataTableSchema = new DataTable ();
-                       dataTableSchema.Columns.Add ("ColumnName", typeof (string));
-                       dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
-                       dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
-                       dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
-                       dataTableSchema.Columns.Add ("NumericScale", typeof (int));
-                       dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsKey", typeof (bool));
-                       dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
-                       dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
-                       dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
-                       dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
-                       dataTableSchema.Columns.Add ("DataType", typeof(string));
-                       dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
-                       dataTableSchema.Columns.Add ("ProviderType", typeof (int));
-                       dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsLong", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
-
-                       fieldCount = PostgresLibrary.PQnfields (pgResult);
-                       rowCount = PostgresLibrary.PQntuples(pgResult);
-                       pgtypes = new string[fieldCount];\r
-
-                       DataRow schemaRow;
-                       int oid;
-                       DbType dbType;
-                       Type typ;
+                               dataTableSchema = new DataTable ();
+                               dataTableSchema.Columns.Add ("ColumnName", typeof (string));
+                               dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
+                               dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
+                               dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
+                               dataTableSchema.Columns.Add ("NumericScale", typeof (int));
+                               dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsKey", typeof (bool));
+                               dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
+                               dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
+                               dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
+                               dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
+                               dataTableSchema.Columns.Add ("DataType", typeof(string));
+                               dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
+                               dataTableSchema.Columns.Add ("ProviderType", typeof (int));
+                               dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsLong", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
+
+                               fieldCount = PostgresLibrary.PQnfields (pgResult);
+                               rowCount = PostgresLibrary.PQntuples(pgResult);
+                               pgtypes = new string[fieldCount];\r
+
+                               DataRow schemaRow;
+                               int oid;
+                               DbType dbType;
+                               Type typ;
                                                
-                       for (int i = 0; i < fieldCount; i += 1 )
-                       {
-                               schemaRow = dataTableSchema.NewRow ();
-
-                               schemaRow["ColumnName"] = PostgresLibrary.PQfname (pgResult, i);
-                               schemaRow["ColumnOrdinal"] = i+1;
-                               schemaRow["ColumnSize"] = PostgresLibrary.PQfsize (pgResult, i);
-                               schemaRow["NumericPrecision"] = 0; // ? tim
-                               schemaRow["NumericScale"] = 0; // ? tim
-                               schemaRow["IsUnique"] = false; // ? tim
-                               schemaRow["IsKey"] = false; // ? tim
-                               schemaRow["BaseCatalogName"] = ""; // ? tim
-                               schemaRow["BaseColumnName"] = PostgresLibrary.PQfname (pgResult, i);
-                               schemaRow["BaseSchemaName"] = ""; // ? tim
-                               schemaRow["BaseTableName"]  = ""; // ? tim
+                               for (int i = 0; i < fieldCount; i += 1 ) {
+                                       schemaRow = dataTableSchema.NewRow ();
+
+                                       schemaRow["ColumnName"] = PostgresLibrary.PQfname (pgResult, i);
+                                       schemaRow["ColumnOrdinal"] = i+1;
+                                       schemaRow["ColumnSize"] = PostgresLibrary.PQfsize (pgResult, i);
+                                       schemaRow["NumericPrecision"] = 0;
+                                       schemaRow["NumericScale"] = 0;
+                                       schemaRow["IsUnique"] = false;
+                                       schemaRow["IsKey"] = false;
+                                       schemaRow["BaseCatalogName"] = "";
+                                       schemaRow["BaseColumnName"] = PostgresLibrary.PQfname (pgResult, i);
+                                       schemaRow["BaseSchemaName"] = "";
+                                       schemaRow["BaseTableName"]  = "";
                                
-                               // PostgreSQL type to .NET type stuff
-                               oid = PostgresLibrary.PQftype (pgResult, i);
-                               pgtypes[i] = PostgresHelper.OidToTypname (oid, con.Types);      \r
-                               dbType = PostgresHelper.TypnameToSqlDbType (pgtypes[i]);\r
+                                       // PostgreSQL type to .NET type stuff
+                                       oid = PostgresLibrary.PQftype (pgResult, i);
+                                       pgtypes[i] = PostgresHelper.OidToTypname (oid, con.Types);      \r
+                                       dbType = PostgresHelper.TypnameToSqlDbType (pgtypes[i]);\r
                                \r
-                               typ = PostgresHelper.DbTypeToSystemType (dbType);\r
-                               string st = typ.ToString();\r
-                               schemaRow["DataType"] = st;\r
-
-                               schemaRow["AllowDBNull"] = false; // ? tim
-                               schemaRow["ProviderType"] = oid; // ? tim
-                               schemaRow["IsAliased"] = false; // ? tim
-                               schemaRow["IsExpression"] = false; // ? tim
-                               schemaRow["IsIdentity"] = false; // ? tim
-                               schemaRow["IsAutoIncrement"] = false; // ? tim
-                               schemaRow["IsRowVersion"] = false; // ? tim
-                               schemaRow["IsHidden"] = false; // ? tim
-                               schemaRow["IsLong"] = false; // ? tim
-                               schemaRow["IsReadOnly"] = false; // ? tim
-                               schemaRow.AcceptChanges();
-                               dataTableSchema.Rows.Add (schemaRow);
-                               
-                       }
+                                       typ = PostgresHelper.DbTypeToSystemType (dbType);\r
+                                       string st = typ.ToString();\r
+                                       schemaRow["DataType"] = st;\r
+
+                                       schemaRow["AllowDBNull"] = false;
+                                       schemaRow["ProviderType"] = oid;
+                                       schemaRow["IsAliased"] = false;
+                                       schemaRow["IsExpression"] = false;
+                                       schemaRow["IsIdentity"] = false;
+                                       schemaRow["IsAutoIncrement"] = false;
+                                       schemaRow["IsRowVersion"] = false;
+                                       schemaRow["IsHidden"] = false;
+                                       schemaRow["IsLong"] = false;
+                                       schemaRow["IsReadOnly"] = false;
+                                       schemaRow.AcceptChanges();
+                                       dataTableSchema.Rows.Add (schemaRow);   
+                               }
 
 #if DEBUG_SqlCommand
-                       Console.WriteLine("********** DEBUG Table Schema BEGIN ************");
-                       foreach (DataRow myRow in dataTableSchema.Rows) {\r
-                               foreach (DataColumn myCol in dataTableSchema.Columns)\r
-                                       Console.WriteLine(myCol.ColumnName + " = " + myRow[myCol]);\r
-                               Console.WriteLine();\r
-                       }
-                       Console.WriteLine("********** DEBUG Table Schema END ************");
+                               Console.WriteLine("********** DEBUG Table Schema BEGIN ************");
+                               foreach (DataRow myRow in dataTableSchema.Rows) {\r
+                                       foreach (DataColumn myCol in dataTableSchema.Columns)\r
+                                               Console.WriteLine(myCol.ColumnName + " = " + myRow[myCol]);\r
+                                       Console.WriteLine();\r
+                               }
+                               Console.WriteLine("********** DEBUG Table Schema END ************");
 #endif // DEBUG_SqlCommand
 
+                       }
                }
        }
 }
index 785fca0669ed04ea555747f9af99541052592251..26a047868426c5e730b96e0eb7d94b93d733c13f 100644 (file)
@@ -45,8 +45,9 @@ namespace System.Data.SqlClient {
 
                #region Fields
 
-               private PostgresTypes types;
+               private PostgresTypes types = null;
                private IntPtr pgConn = IntPtr.Zero;    
+
                // PGConn (Postgres Connection)
                private string connectionString = "";    
                // OLE DB Connection String
@@ -82,7 +83,11 @@ namespace System.Data.SqlClient {
                // support SSL. Set to 0 (default) to 
                // negotiate with server. 
 
+               // connection state
                private ConnectionState conState = ConnectionState.Closed;
+               
+               // DataReader state
+               private SqlDataReader rdr = null;
                private bool dataReaderOpen = false;
                // FIXME: if true, throw an exception if SqlConnection 
                //        is used for anything other than reading
@@ -167,6 +172,12 @@ namespace System.Data.SqlClient {
                                
                [MonoTODO]
                public void Close () {
+                       if(dataReaderOpen == true) {
+                               // TODO: what do I do if
+                               // the user Closes the connection
+                               // without closing the Reader first?
+
+                       }                       
                        CloseDataSource ();
                }
 
@@ -235,6 +246,40 @@ namespace System.Data.SqlClient {
 
                #endregion
 
+               #region Internal Methods
+
+               // Used to prevent SqlConnection
+               // from doing anything while
+               // SqlDataReader is open.
+               // Open the Reader. (called from SqlCommand)
+               internal void OpenReader(SqlDataReader reader) 
+               {       
+                       if(dataReaderOpen == true) {
+                               // TODO: throw exception here?
+                               //       because a reader
+                               //       is already open
+                       }
+                       else {
+                               rdr = reader;
+                               dataReaderOpen = true;
+                       }
+               }
+
+               // Used to prevent SqlConnection
+               // from doing anything while
+               // SqlDataReader is open
+               // Close the Reader (called from SqlCommand)
+               // if closeConnection true, Close() the connection
+               // this is based on CommandBehavior.CloseConnection
+               internal void CloseReader(bool closeConnection)
+               {       if(closeConnection == true)
+                               CloseDataSource();
+                       else
+                               dataReaderOpen = false;
+               }
+
+               #endregion // Internal Methods
+
                #region Private Methods
 
                private void SetupConnection() {
@@ -261,9 +306,11 @@ namespace System.Data.SqlClient {
 
                private void CloseDataSource () {
                        // FIXME: just a quick hack
-                       conState = ConnectionState.Closed;
-                       PostgresLibrary.PQfinish (pgConn);
-                       pgConn = IntPtr.Zero;
+                       if(conState == ConnectionState.Open) {
+                               conState = ConnectionState.Closed;
+                               PostgresLibrary.PQfinish (pgConn);
+                               pgConn = IntPtr.Zero;
+                       }
                }
 
                private void SetConnectionString (string connectionString) {
@@ -515,13 +562,10 @@ namespace System.Data.SqlClient {
                // Used to prevent SqlConnection
                // from doing anything while
                // SqlDataReader is open
-               internal bool OpenReader {
+               internal bool IsReaderOpen {
                        get {
                                return dataReaderOpen;
                        }
-                       set {
-                               dataReaderOpen = value;
-                       }
                }
 
                #endregion // Internal Properties
index 6d55d61673a820f32770d4c089b88670181b21ab..28d0e1bc4e725012ab50bcbd4a281d4adef64e9a 100644 (file)
@@ -68,6 +68,7 @@ namespace System.Data.SqlClient {
 
                        cmd = sqlCmd;
                        open = true;
+                       cmd.OpenReader(this);
                }
 
                #endregion
@@ -98,18 +99,30 @@ namespace System.Data.SqlClient {
                public bool NextResult() {
                        SqlResult res;
                        currentRow = -1;
+                       bool resultReturned;
                        
+                       // reset
+                       table = null;
+                       pgResult = IntPtr.Zero;
+                       rows = 0;
+                       cols = 0;
+                       types = null;
+                       recordsAffected = -1;
+
                        res = cmd.NextResult();
+                       resultReturned = res.ResultReturned;
 
-                       if(res.ResultReturned == true) {
+                       if(resultReturned == true) {
                                table = res.Table;
                                pgResult = res.PgResult;
                                rows = res.RowCount;
                                cols = res.FieldCount;
                                types = res.PgTypes;
+                               recordsAffected = res.RecordsAffected;
                        }
-
-                       return res.ResultReturned;
+                       
+                       res = null;
+                       return resultReturned;
                }
 
                [MonoTODO]
index 5d3e63ec1d37a5fe5271515c4f1f8550172a4418..7aed0df4484a10597cecae2730497bd0a9f1ff7f 100644 (file)
@@ -1,3 +1,44 @@
+2002-05-26  Daniel Morgan <danmorg@sc.rr.com>
+
+       * Test/SqlSharpCli.cs: added file
+       My new toy.  SQL# is a command-line tool to enter
+       SQL     commands and queries using Mono System.Data.
+       It also serves as a test for Mono System.Data.
+       
+       * System.Data.SqlClient/SqlCommand.cs: modified
+       - ExecuteNonQuery(), ExecuteScalar(), and ExecuteReader()
+       should handle the results from SQL Commands and Queries.
+       - Internal class SqlResult should not create schema Table
+       for the result from a SQL Command.  Also, set the RecordsRetrieved
+       property for SqlDataReader.
+       - Closing the SqlDataReader should Close() the SqlConnection for
+       a CommandBehavior.CloseConnection.
+       - Set defaults for SqlResult
+       
+       * System.Data.SqlClient/SqlConnection.cs: modified - 
+       when SqlDataReader is Close()
+       should Close() the SqlConnection for
+       a CommandBehavior.CloseConnection.  Changed internal Property
+       from OpenReader get/set to IsReaderOpen get and created
+       internal methods OpenReader()/CloseReader() for SqlCommand to call.
+       SqlConnection needs to be prevented from doing while SqlDataReader
+       is being used.
+       
+       * System.Data.SqlClient/SqlDataReader.cs: modified -
+       call SqlCommand's OpenReader() internal method.  get
+       RecordsRetrieved from SqlResult.  set/reset default
+       values for SqlDataReader.
+       
+       * Test/PostgresTest.cs
+       * Test/TestExecuteScalar.cs
+       * Test/TestSqlDataReader.cs: modified
+       for the Execute...() methods in SqlCommand
+       to test SQL Queries and Commands
+       
+       * Test/System.Data_test.build: modified
+       exclude new file Test/SqlSharpCli.cs from 
+       test build
+       
 2002-05-24  Tim Coleman <tim@timcoleman.com>
        * System.Data.Common/DbDataAdapter.cs: remove IDbCommands, except
        for get accessors.  These should be implemented in derived classes.  See
index f9064516c02d722097e456c435105bb40aa50e14..1d4c8c5bc9ca3b2c5c44694ce16da3230655d7d0 100644 (file)
@@ -135,7 +135,9 @@ namespace System.Data.SqlClient {
                        execStatus = PostgresLibrary.
                                PQresultStatus (pgResult);
                        
-                       if(execStatus == ExecStatusType.PGRES_COMMAND_OK) {
+                       if(execStatus == ExecStatusType.PGRES_COMMAND_OK ||
+                               execStatus == ExecStatusType.PGRES_TUPLES_OK ) {
+
                                rowsAffectedString = PostgresLibrary.
                                        PQcmdTuples (pgResult);
 
@@ -317,7 +319,11 @@ namespace System.Data.SqlClient {
                        execStatus = PostgresLibrary.
                                PQresultStatus (pgResult);
                        
-                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
+                       res.ExecStatus = execStatus;
+
+                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK ||
+                               execStatus == ExecStatusType.PGRES_COMMAND_OK) {
+
                                res.BuildTableSchema(pgResult);
                        }
                        else {
@@ -343,9 +349,21 @@ namespace System.Data.SqlClient {
                // those resources.  Also, need to allow this SqlCommand
                // and this SqlConnection to do things again.
                internal void CloseReader() {
-                       conn.OpenReader = false;
                        dataReader = null;
                        queries = null;
+
+                       if((cmdBehavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection) {
+                               conn.CloseReader(true);
+                       }
+                       else {
+                               conn.CloseReader(false);
+                       }
+               }
+
+               // only meant to be used between SqlConnectioin,
+               // SqlCommand, and SqlDataReader
+               internal void OpenReader(SqlDataReader reader) {
+                       conn.OpenReader(reader);
                }
 
                /// <summary>\r
@@ -385,8 +403,18 @@ namespace System.Data.SqlClient {
 
                        execStatus = PostgresLibrary.
                                PQresultStatus (pgResult);
-                       
-                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
+                       if(execStatus == ExecStatusType.PGRES_COMMAND_OK) {
+                               // result was a SQL Command 
+
+                               // close result set
+                               PostgresLibrary.PQclear (pgResult);
+                               pgResult = IntPtr.Zero;
+
+                               return null; // return null reference
+                       }
+                       else if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
+                               // result was a SQL Query
+
                                nRows = PostgresLibrary.
                                        PQntuples(pgResult);
 
@@ -648,13 +676,24 @@ namespace System.Data.SqlClient {
        // from SqlCommand to SqlDataReader
        internal class SqlResult {
 
-               private DataTable dataTableSchema; // only will contain the schema
-               private IntPtr pg_result; // native PostgreSQL PGresult
-               private int rowCount; 
-               private int fieldCount;
-               private string[] pgtypes; // PostgreSQL types (typname)
+               private DataTable dataTableSchema = null; // only will contain the schema
+               private IntPtr pg_result = IntPtr.Zero; // native PostgreSQL PGresult
+               private int rowCount = 0
+               private int fieldCount = 0;
+               private string[] pgtypes = null; // PostgreSQL types (typname)
                private bool resultReturned = false;
-               private SqlConnection con;
+               private SqlConnection con = null;
+               private int rowsAffected = -1;
+               private ExecStatusType execStatus = ExecStatusType.PGRES_FATAL_ERROR;
+
+               internal ExecStatusType ExecStatus {
+                       get {
+                               return execStatus;
+                       }
+                       set {
+                               execStatus = value;
+                       }
+               }
 
                internal SqlConnection Connection {
                        set {
@@ -662,6 +701,12 @@ namespace System.Data.SqlClient {
                        }
                }
 
+               internal int RecordsAffected {
+                       get {
+                               return rowsAffected;
+                       }
+               }
+
                internal bool ResultReturned {
                        get {
                                return resultReturned;
@@ -701,93 +746,104 @@ namespace System.Data.SqlClient {
                        }
                }
 
-               internal void BuildTableSchema (IntPtr pgResult) 
-               {
+               internal void BuildTableSchema (IntPtr pgResult) {
                        pg_result = pgResult;
+                       
+                       // need to set IDataReader.RecordsAffected property
+                       string rowsAffectedString;
+                       rowsAffectedString = PostgresLibrary.
+                               PQcmdTuples (pgResult);
+                       if(rowsAffectedString != null)
+                               if(rowsAffectedString.Equals("") == false)
+                                       rowsAffected = int.Parse(rowsAffectedString);
+                       
+                       // Only Results from SQL SELECT Queries 
+                       // get a DataTable for schema of the result
+                       // otherwise, DataTable is null reference
+                       if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
 
-                       dataTableSchema = new DataTable ();
-                       dataTableSchema.Columns.Add ("ColumnName", typeof (string));
-                       dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
-                       dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
-                       dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
-                       dataTableSchema.Columns.Add ("NumericScale", typeof (int));
-                       dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsKey", typeof (bool));
-                       dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
-                       dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
-                       dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
-                       dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
-                       dataTableSchema.Columns.Add ("DataType", typeof(string));
-                       dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
-                       dataTableSchema.Columns.Add ("ProviderType", typeof (int));
-                       dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsLong", typeof (bool));
-                       dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
-
-                       fieldCount = PostgresLibrary.PQnfields (pgResult);
-                       rowCount = PostgresLibrary.PQntuples(pgResult);
-                       pgtypes = new string[fieldCount];\r
-
-                       DataRow schemaRow;
-                       int oid;
-                       DbType dbType;
-                       Type typ;
+                               dataTableSchema = new DataTable ();
+                               dataTableSchema.Columns.Add ("ColumnName", typeof (string));
+                               dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
+                               dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
+                               dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
+                               dataTableSchema.Columns.Add ("NumericScale", typeof (int));
+                               dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsKey", typeof (bool));
+                               dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
+                               dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
+                               dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
+                               dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
+                               dataTableSchema.Columns.Add ("DataType", typeof(string));
+                               dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
+                               dataTableSchema.Columns.Add ("ProviderType", typeof (int));
+                               dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsLong", typeof (bool));
+                               dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
+
+                               fieldCount = PostgresLibrary.PQnfields (pgResult);
+                               rowCount = PostgresLibrary.PQntuples(pgResult);
+                               pgtypes = new string[fieldCount];\r
+
+                               DataRow schemaRow;
+                               int oid;
+                               DbType dbType;
+                               Type typ;
                                                
-                       for (int i = 0; i < fieldCount; i += 1 )
-                       {
-                               schemaRow = dataTableSchema.NewRow ();
-
-                               schemaRow["ColumnName"] = PostgresLibrary.PQfname (pgResult, i);
-                               schemaRow["ColumnOrdinal"] = i+1;
-                               schemaRow["ColumnSize"] = PostgresLibrary.PQfsize (pgResult, i);
-                               schemaRow["NumericPrecision"] = 0; // ? tim
-                               schemaRow["NumericScale"] = 0; // ? tim
-                               schemaRow["IsUnique"] = false; // ? tim
-                               schemaRow["IsKey"] = false; // ? tim
-                               schemaRow["BaseCatalogName"] = ""; // ? tim
-                               schemaRow["BaseColumnName"] = PostgresLibrary.PQfname (pgResult, i);
-                               schemaRow["BaseSchemaName"] = ""; // ? tim
-                               schemaRow["BaseTableName"]  = ""; // ? tim
+                               for (int i = 0; i < fieldCount; i += 1 ) {
+                                       schemaRow = dataTableSchema.NewRow ();
+
+                                       schemaRow["ColumnName"] = PostgresLibrary.PQfname (pgResult, i);
+                                       schemaRow["ColumnOrdinal"] = i+1;
+                                       schemaRow["ColumnSize"] = PostgresLibrary.PQfsize (pgResult, i);
+                                       schemaRow["NumericPrecision"] = 0;
+                                       schemaRow["NumericScale"] = 0;
+                                       schemaRow["IsUnique"] = false;
+                                       schemaRow["IsKey"] = false;
+                                       schemaRow["BaseCatalogName"] = "";
+                                       schemaRow["BaseColumnName"] = PostgresLibrary.PQfname (pgResult, i);
+                                       schemaRow["BaseSchemaName"] = "";
+                                       schemaRow["BaseTableName"]  = "";
                                
-                               // PostgreSQL type to .NET type stuff
-                               oid = PostgresLibrary.PQftype (pgResult, i);
-                               pgtypes[i] = PostgresHelper.OidToTypname (oid, con.Types);      \r
-                               dbType = PostgresHelper.TypnameToSqlDbType (pgtypes[i]);\r
+                                       // PostgreSQL type to .NET type stuff
+                                       oid = PostgresLibrary.PQftype (pgResult, i);
+                                       pgtypes[i] = PostgresHelper.OidToTypname (oid, con.Types);      \r
+                                       dbType = PostgresHelper.TypnameToSqlDbType (pgtypes[i]);\r
                                \r
-                               typ = PostgresHelper.DbTypeToSystemType (dbType);\r
-                               string st = typ.ToString();\r
-                               schemaRow["DataType"] = st;\r
-
-                               schemaRow["AllowDBNull"] = false; // ? tim
-                               schemaRow["ProviderType"] = oid; // ? tim
-                               schemaRow["IsAliased"] = false; // ? tim
-                               schemaRow["IsExpression"] = false; // ? tim
-                               schemaRow["IsIdentity"] = false; // ? tim
-                               schemaRow["IsAutoIncrement"] = false; // ? tim
-                               schemaRow["IsRowVersion"] = false; // ? tim
-                               schemaRow["IsHidden"] = false; // ? tim
-                               schemaRow["IsLong"] = false; // ? tim
-                               schemaRow["IsReadOnly"] = false; // ? tim
-                               schemaRow.AcceptChanges();
-                               dataTableSchema.Rows.Add (schemaRow);
-                               
-                       }
+                                       typ = PostgresHelper.DbTypeToSystemType (dbType);\r
+                                       string st = typ.ToString();\r
+                                       schemaRow["DataType"] = st;\r
+
+                                       schemaRow["AllowDBNull"] = false;
+                                       schemaRow["ProviderType"] = oid;
+                                       schemaRow["IsAliased"] = false;
+                                       schemaRow["IsExpression"] = false;
+                                       schemaRow["IsIdentity"] = false;
+                                       schemaRow["IsAutoIncrement"] = false;
+                                       schemaRow["IsRowVersion"] = false;
+                                       schemaRow["IsHidden"] = false;
+                                       schemaRow["IsLong"] = false;
+                                       schemaRow["IsReadOnly"] = false;
+                                       schemaRow.AcceptChanges();
+                                       dataTableSchema.Rows.Add (schemaRow);   
+                               }
 
 #if DEBUG_SqlCommand
-                       Console.WriteLine("********** DEBUG Table Schema BEGIN ************");
-                       foreach (DataRow myRow in dataTableSchema.Rows) {\r
-                               foreach (DataColumn myCol in dataTableSchema.Columns)\r
-                                       Console.WriteLine(myCol.ColumnName + " = " + myRow[myCol]);\r
-                               Console.WriteLine();\r
-                       }
-                       Console.WriteLine("********** DEBUG Table Schema END ************");
+                               Console.WriteLine("********** DEBUG Table Schema BEGIN ************");
+                               foreach (DataRow myRow in dataTableSchema.Rows) {\r
+                                       foreach (DataColumn myCol in dataTableSchema.Columns)\r
+                                               Console.WriteLine(myCol.ColumnName + " = " + myRow[myCol]);\r
+                                       Console.WriteLine();\r
+                               }
+                               Console.WriteLine("********** DEBUG Table Schema END ************");
 #endif // DEBUG_SqlCommand
 
+                       }
                }
        }
 }
index 785fca0669ed04ea555747f9af99541052592251..26a047868426c5e730b96e0eb7d94b93d733c13f 100644 (file)
@@ -45,8 +45,9 @@ namespace System.Data.SqlClient {
 
                #region Fields
 
-               private PostgresTypes types;
+               private PostgresTypes types = null;
                private IntPtr pgConn = IntPtr.Zero;    
+
                // PGConn (Postgres Connection)
                private string connectionString = "";    
                // OLE DB Connection String
@@ -82,7 +83,11 @@ namespace System.Data.SqlClient {
                // support SSL. Set to 0 (default) to 
                // negotiate with server. 
 
+               // connection state
                private ConnectionState conState = ConnectionState.Closed;
+               
+               // DataReader state
+               private SqlDataReader rdr = null;
                private bool dataReaderOpen = false;
                // FIXME: if true, throw an exception if SqlConnection 
                //        is used for anything other than reading
@@ -167,6 +172,12 @@ namespace System.Data.SqlClient {
                                
                [MonoTODO]
                public void Close () {
+                       if(dataReaderOpen == true) {
+                               // TODO: what do I do if
+                               // the user Closes the connection
+                               // without closing the Reader first?
+
+                       }                       
                        CloseDataSource ();
                }
 
@@ -235,6 +246,40 @@ namespace System.Data.SqlClient {
 
                #endregion
 
+               #region Internal Methods
+
+               // Used to prevent SqlConnection
+               // from doing anything while
+               // SqlDataReader is open.
+               // Open the Reader. (called from SqlCommand)
+               internal void OpenReader(SqlDataReader reader) 
+               {       
+                       if(dataReaderOpen == true) {
+                               // TODO: throw exception here?
+                               //       because a reader
+                               //       is already open
+                       }
+                       else {
+                               rdr = reader;
+                               dataReaderOpen = true;
+                       }
+               }
+
+               // Used to prevent SqlConnection
+               // from doing anything while
+               // SqlDataReader is open
+               // Close the Reader (called from SqlCommand)
+               // if closeConnection true, Close() the connection
+               // this is based on CommandBehavior.CloseConnection
+               internal void CloseReader(bool closeConnection)
+               {       if(closeConnection == true)
+                               CloseDataSource();
+                       else
+                               dataReaderOpen = false;
+               }
+
+               #endregion // Internal Methods
+
                #region Private Methods
 
                private void SetupConnection() {
@@ -261,9 +306,11 @@ namespace System.Data.SqlClient {
 
                private void CloseDataSource () {
                        // FIXME: just a quick hack
-                       conState = ConnectionState.Closed;
-                       PostgresLibrary.PQfinish (pgConn);
-                       pgConn = IntPtr.Zero;
+                       if(conState == ConnectionState.Open) {
+                               conState = ConnectionState.Closed;
+                               PostgresLibrary.PQfinish (pgConn);
+                               pgConn = IntPtr.Zero;
+                       }
                }
 
                private void SetConnectionString (string connectionString) {
@@ -515,13 +562,10 @@ namespace System.Data.SqlClient {
                // Used to prevent SqlConnection
                // from doing anything while
                // SqlDataReader is open
-               internal bool OpenReader {
+               internal bool IsReaderOpen {
                        get {
                                return dataReaderOpen;
                        }
-                       set {
-                               dataReaderOpen = value;
-                       }
                }
 
                #endregion // Internal Properties
index 6d55d61673a820f32770d4c089b88670181b21ab..28d0e1bc4e725012ab50bcbd4a281d4adef64e9a 100644 (file)
@@ -68,6 +68,7 @@ namespace System.Data.SqlClient {
 
                        cmd = sqlCmd;
                        open = true;
+                       cmd.OpenReader(this);
                }
 
                #endregion
@@ -98,18 +99,30 @@ namespace System.Data.SqlClient {
                public bool NextResult() {
                        SqlResult res;
                        currentRow = -1;
+                       bool resultReturned;
                        
+                       // reset
+                       table = null;
+                       pgResult = IntPtr.Zero;
+                       rows = 0;
+                       cols = 0;
+                       types = null;
+                       recordsAffected = -1;
+
                        res = cmd.NextResult();
+                       resultReturned = res.ResultReturned;
 
-                       if(res.ResultReturned == true) {
+                       if(resultReturned == true) {
                                table = res.Table;
                                pgResult = res.PgResult;
                                rows = res.RowCount;
                                cols = res.FieldCount;
                                types = res.PgTypes;
+                               recordsAffected = res.RecordsAffected;
                        }
-
-                       return res.ResultReturned;
+                       
+                       res = null;
+                       return resultReturned;
                }
 
                [MonoTODO]
index 276d9d848219e18f51cb1fd2f0180b5a2f55bd3e..645673185e665512bbd93f37583138b90b0b31e6 100644 (file)
@@ -38,6 +38,7 @@ namespace TestSystemDataSqlClient {
 
        class PostgresTest {
 
+               // execute SQL CREATE TABLE Command using ExecuteNonQuery()
                static void CreateTable (IDbConnection cnc) {
                                                
                        IDbCommand createCommand = cnc.CreateCommand();
@@ -77,6 +78,7 @@ namespace TestSystemDataSqlClient {
                        createCommand.ExecuteNonQuery ();
                }
 
+               // execute SQL DROP TABLE Command using ExecuteNonQuery
                static void DropTable (IDbConnection cnc) {
                                 
                        IDbCommand dropCommand = cnc.CreateCommand ();
@@ -87,6 +89,7 @@ namespace TestSystemDataSqlClient {
                        dropCommand.ExecuteNonQuery ();
                }
 
+               // execute stored procedure using ExecuteScalar()
                static object CallStoredProcedure (IDbConnection cnc) {
                                 
                        IDbCommand callStoredProcCommand = cnc.CreateCommand ();
@@ -102,6 +105,7 @@ namespace TestSystemDataSqlClient {
                        return data;
                }
 
+               // execute SQL INSERT Command using ExecuteNonQuery()
                static void InsertData (IDbConnection cnc) {            
 
                        IDbCommand insertCommand = cnc.CreateCommand();
@@ -142,12 +146,15 @@ namespace TestSystemDataSqlClient {
                        insertCommand.ExecuteNonQuery ();
                }
 
+               // execute a SQL SELECT Query using ExecuteReader() to retrieve
+               // a IDataReader so we retrieve data
                static IDataReader SelectData (IDbConnection cnc) {
        
                        IDbCommand selectCommand = cnc.CreateCommand();
                        IDataReader reader;
 
                        // FIXME: System.Data classes need to handle NULLs
+                       //        this would be done by System.DBNull ?
                        // FIXME: System.Data needs to handle more data types
                        /*
                        selectCommand.CommandText = 
@@ -192,6 +199,70 @@ namespace TestSystemDataSqlClient {
                        return reader;
                }
 
+               // Tests a SQL Command (INSERT, UPDATE, DELETE)
+               // executed via ExecuteReader
+               static IDataReader SelectDataUsingInsertCommand (IDbConnection cnc) {
+       
+                       IDbCommand selectCommand = cnc.CreateCommand();
+                       IDataReader reader;
+
+                       // This is a SQL INSERT Command, not a Query
+                       selectCommand.CommandText = 
+                               "insert into mono_postgres_test (" +
+                               "boolean_value, " +
+                               "int2_value, " +
+                               "int4_value, " +
+                               "bigint_value, " +
+                               "float_value, " +
+                               "double_value, " +
+                               "numeric_value, " +
+                               "char_value, " +
+                               "varchar_value, " +
+                               "text_value, " +
+                               "time_value, " +
+                               "date_value, " +
+                               "timestamp_value, " +
+                               "point_value " +
+                               ") values (" +
+                               "'T', " +
+                               "-22, " +
+                               "1048000, " +
+                               "123456789012345, " +
+                               "3.141592, " +
+                               "3.1415926969696, " +
+                               "123456789012.345, " +
+                               "'This is a char', " +
+                               "'This is a varchar', " +
+                               "'This is a text', " +
+                               "'21:13:14', " +
+                               "'2000-02-29', " +
+                               "'2004-02-29 14:00:11.31', " +
+                               "'(1,0)' " +
+                               ")";
+
+                       reader = selectCommand.ExecuteReader ();
+
+                       return reader;
+               }
+
+               // Tests a SQL Command not (INSERT, UPDATE, DELETE)
+               // executed via ExecuteReader
+               static IDataReader SelectDataUsingCommand (IDbConnection cnc) {
+       
+                       IDbCommand selectCommand = cnc.CreateCommand();
+                       IDataReader reader;
+
+                       // This is a SQL Command, not a Query
+                       selectCommand.CommandText = 
+                               "SET DATESTYLE TO 'ISO'";
+
+                       reader = selectCommand.ExecuteReader ();
+
+                       return reader;
+               }
+
+
+               // execute an SQL UPDATE Command using ExecuteNonQuery()
                static void UpdateData (IDbConnection cnc) {
        
                        IDbCommand updateCommand = cnc.CreateCommand();         
@@ -199,19 +270,20 @@ namespace TestSystemDataSqlClient {
                        updateCommand.CommandText = 
                                "update mono_postgres_test " +                          
                                "set " +
-                                       "boolean_value = 'F', " +
-                                       "int2_value    = 5, " +
-                                       "int4_value    = 3, " +
-                                       "bigint_value  = 9, " +
-                                       "char_value    = 'Mono.Data!'   , " +
-                                       "varchar_value = 'It was not me!', " +
-                                       "text_value    = 'We got data!'   " +
+                               "boolean_value = 'F', " +
+                               "int2_value    = 5, " +
+                               "int4_value    = 3, " +
+                               "bigint_value  = 9, " +
+                               "char_value    = 'Mono.Data!'   , " +
+                               "varchar_value = 'It was not me!', " +
+                               "text_value    = 'We got data!'   " +
                                "where int2_value = -22";
 
                        updateCommand.ExecuteNonQuery ();               
                }
 
                // used to do a min(), max(), count(), sum(), or avg()
+               // execute SQL SELECT Query using ExecuteScalar
                static object SelectAggregate (IDbConnection cnc, String agg) {
        
                        IDbCommand selectCommand = cnc.CreateCommand();
@@ -231,6 +303,99 @@ namespace TestSystemDataSqlClient {
                        return data;
                }
 
+               // used internally by ReadData() to read each result set
+               static void ReadResult(IDataReader rdr, DataTable dt) {
+                                               \r
+                       // number of columns in the table\r
+                       Console.WriteLine("   Total Columns: " +\r
+                               dt.Rows.Count);\r
+\r
+                       // display the schema\r
+                       foreach (DataRow schemaRow in dt.Rows) {\r
+                               foreach (DataColumn schemaCol in dt.Columns)\r
+                                       Console.WriteLine(schemaCol.ColumnName + \r
+                                               " = " + \r
+                                               schemaRow[schemaCol]);\r
+                               Console.WriteLine();\r
+                       }\r
+\r
+                       int nRows = 0;\r
+                       int c = 0;\r
+                       string output, metadataValue, dataValue;\r
+                       // Read and display the rows\r
+                       Console.WriteLine("Gonna do a Read() now...");\r
+                       while(rdr.Read()) {\r
+                               Console.WriteLine("   Row " + nRows + ": ");\r
+                                       \r
+                               for(c = 0; c < rdr.FieldCount; c++) {\r
+                                       // column meta data \r
+                                       DataRow dr = dt.Rows[c];\r
+                                       metadataValue = \r
+                                               "    Col " + \r
+                                               c + ": " + \r
+                                               dr["ColumnName"];\r
+                                               \r
+                                       // column data\r
+                                       if(rdr.IsDBNull(c) == true)\r
+                                               dataValue = " is NULL";\r
+                                       else\r
+                                               dataValue = \r
+                                                       ": " + \r
+                                                       rdr.GetValue(c);\r
+                                       \r
+                                       // display column meta data and data\r
+                                       output = metadataValue + dataValue;                                     \r
+                                       Console.WriteLine(output);\r
+                               }\r
+                               nRows++;\r
+                       }\r
+                       Console.WriteLine("   Total Rows Retrieved: " + \r
+                               nRows); 
+               }
+
+               // Used to read data from IDataReader after calling IDbCommand:ExecuteReader()
+               static void ReadData(IDataReader rdr) {
+
+                       int results = 0;
+                       if(rdr == null) {
+               
+                               Console.WriteLine("IDataReader has a Null Reference.");
+                       }
+                       else {
+                               do {\r
+                                       DataTable dt = rdr.GetSchemaTable();\r
+                                       if(rdr.RecordsAffected != -1) {\r
+                                               // Results for \r
+                                               // SQL INSERT, UPDATE, DELETE Commands \r
+                                               // have RecordsAffected >= 0\r
+                                               Console.WriteLine("Result is from a SQL Command (INSERT,UPDATE,DELETE).  Records Affected: " + rdr.RecordsAffected);\r
+                                       }\r
+                                       else if(dt == null)\r
+                                               // Results for\r
+                                               // SQL Commands not INSERT, UPDATE, nor DELETE\r
+                                               // have RecordsAffected == -1\r
+                                               // and GetSchemaTable() returns a null reference\r
+                                               Console.WriteLine("Result is from a SQL Command not (INSERT,UPDATE,DELETE).   Records Affected: " + rdr.RecordsAffected);\r
+                                       else {\r
+                                               // Results for\r
+                                               // SQL SELECT Queries\r
+                                               // have RecordsAffected = -1\r
+                                               // and GetSchemaTable() returns a reference to a DataTable\r
+                                               Console.WriteLine("Result is from a SELECT SQL Query.  Records Affected: " + rdr.RecordsAffected);\r
+               \r
+                                               results++;\r
+                                               Console.WriteLine("Result Set " + results + "...");\r
+\r
+                                               ReadResult(rdr, dt);\r
+                                       }\r
+\r
+                               } while(rdr.NextResult());\r
+                               Console.WriteLine("Total Result sets: " + results);\r
+                       \r
+                               rdr.Close();
+                       }
+               }
+               
                /* Postgres provider tests */
                static void DoPostgresTest (IDbConnection cnc) {
 
@@ -272,6 +437,11 @@ namespace TestSystemDataSqlClient {
 
                                /* Select aggregates */
                                SelectAggregate (cnc, "count(*)");
+                               // FIXME: still having a problem with avg()
+                               //        because it returns a decimal.
+                               //        It may have something to do
+                               //        with culture not being set
+                               //        properly.
                                //SelectAggregate (cnc, "avg(int4_value)");
                                SelectAggregate (cnc, "min(text_value)");
                                SelectAggregate (cnc, "max(int4_value)");
@@ -280,59 +450,19 @@ namespace TestSystemDataSqlClient {
                                /* Select values */
                                Console.WriteLine ("\t\tSelect values from the database: ");
                                reader = SelectData (cnc);
-
-                                // get the DataTable that holds\r
-                               // the schema\r
-                               Console.WriteLine("\t\tGet Schema.");\r
-                               DataTable dt = reader.GetSchemaTable();\r
-                       \r
-                               // number of columns in the table\r
-                               Console.WriteLine("Columns Count: " +\r
-                                       dt.Columns.Count);\r
-\r
-                               int c;\r
-                               // display the schema\r
-                               foreach (DataRow schemaRow in dt.Rows) {\r
-                                       foreach (DataColumn schemaCol in dt.Columns)\r
-                                               Console.WriteLine(schemaCol.ColumnName + \r
-                                                       " = " + \r
-                                                       schemaRow[schemaCol]);\r
-                                       Console.WriteLine();\r
-                               }\r
-\r
-                               int nRows = 0;\r
-                               string metadataValue;\r
-                               string dataValue;\r
-                               string output;\r
-                               // Read and display the rows\r
-                               while(reader.Read()) {\r
-                                       Console.WriteLine ("Row " + nRows + ":");\r
-                                       for(c = 0; c < reader.FieldCount; c++) {\r
-                                               \r
-                                               // column meta data \r
-                                               DataRow dr = dt.Rows[c];\r
-                                               metadataValue = \r
-                                                       "    Col " + \r
-                                                       c + ": " + \r
-                                                       dr["ColumnName"];\r
-                                               \r
-                                               // column data\r
-                                               if(reader.IsDBNull(c) == true)\r
-                                                       dataValue = " is NULL";\r
-                                               else\r
-                                                       dataValue = \r
-                                                               ": " + \r
-                                                               reader.GetValue(c);\r
-                                       \r
-                                               // display column meta data and data\r
-                                               output = metadataValue + dataValue;                                     \r
-                                               Console.WriteLine(output);\r
-                                       }\r
-       \r
-                                       nRows++;\r
-                               }\r
-                               reader.Close();\r
-                               Console.WriteLine ("Rows: " + nRows);           \r
+                               ReadData(reader);
+
+                               /* SQL Command via ExecuteReader/SqlDataReader */
+                               /* Command is not INSERT, UPDATE, or DELETE */
+                               Console.WriteLine("\t\tCall ExecuteReader with a SQL Command. (Not INSERT,UPDATE,DELETE).");
+                               reader = SelectDataUsingCommand(cnc);
+                               ReadData(reader);
+
+                               /* SQL Command via ExecuteReader/SqlDataReader */
+                               /* Command is INSERT, UPDATE, or DELETE */
+                               Console.WriteLine("\t\tCall ExecuteReader with a SQL Command. (Is INSERT,UPDATE,DELETE).");
+                               reader = SelectDataUsingInsertCommand(cnc);
+                               ReadData(reader);
 \r
                                // Call a Stored Procedure named Version()\r
                                Console.WriteLine("\t\tCalling stored procedure version()");\r
@@ -354,14 +484,13 @@ namespace TestSystemDataSqlClient {
                }
 
                [STAThread]\r
-               static void Main(string[] args)\r
-               {\r
+               static void Main(string[] args) {\r
                        SqlConnection cnc = new SqlConnection ();\r
 \r
                        /*\r
                        string connectionString = 
-                               "host=localhost;" +
-                               "dbname=test;" +
+                               "host=hostname;" +
+                               "dbname=database;" +
                                "user=userid;" +
                                "password=password";
                        */\r
@@ -375,7 +504,6 @@ namespace TestSystemDataSqlClient {
 \r
                        cnc.Open();\r
                        DoPostgresTest(cnc);
-
                        cnc.Close();
                }
        }
diff --git a/mcs/class/System.Data/Test/SqlSharpCli.cs b/mcs/class/System.Data/Test/SqlSharpCli.cs
new file mode 100644 (file)
index 0000000..b221f3a
--- /dev/null
@@ -0,0 +1,363 @@
+//
+// SqlSharpCli.cs - main driver for SqlSharp
+//
+//                    Currently, only working on a command line interface for SqlSharp
+//
+//                    However, once GTK# and System.Windows.Forms are good-to-go,
+//                    I would like to create a SqlSharpGui using this.
+//
+//                    It would be nice if this is included as part of Mono
+//                    extra goodies under Mono.Data.SqlSharp.
+//
+//                    Also, this makes a good Test program for Mono System.Data.
+//                    For more information about Mono::, 
+//                    visit http://www.go-mono.com/
+//
+// Author:
+//    Daniel Morgan <danmorg@sc.rr.com>
+//
+// (C)Copyright 2002 Daniel Morgan
+//
+
+using System;
+using System.Data;
+using System.Data.Common;
+using System.Data.SqlClient;
+using System.Text;
+
+namespace Mono.Data.SqlSharp {
+       
+       // SQL Sharp - Command Line Interface
+       public class SqlSharpCli {
+       
+               private IDbConnection conn = null;
+               string provider = "POSTGRESCLIENT";
+               // string connectionString = "server=DANPC;database=pubs;uid=sa;pwd=freetds";
+               string connectionString = "host=localhost;dbname=test;user=postgres";
+
+               public void DisplayResult(IDataReader reader, DataTable schemaTable) {
+
+                       StringBuilder line = null;
+                       string lineOut;
+
+                       int spacing = 0;
+                       int columnSize = 0;
+                       
+                       char spacingChar = ' '; // a space
+                       line = new StringBuilder();
+                       Console.WriteLine("Fields in Query Result: " + reader.FieldCount);
+                       
+                       foreach(DataRow schemaRow in schemaTable.Rows) {
+                               string columnHeader = (string) schemaRow["ColumnName"];
+                               int columnHeaderSize = columnHeader.Length;
+                               line.Append(columnHeader);
+                               line.Append(" ");
+                                       
+                               // spacing
+                               columnSize = (int) schemaRow["ColumnSize"];
+                               if(columnHeaderSize < columnSize) {
+                                       spacing = columnSize - columnHeaderSize;
+                                       line.Append(spacingChar, spacing);
+                               }
+
+                       }
+                       lineOut = line.ToString();
+                       Console.WriteLine(line);
+                       line = null;
+                       line = new StringBuilder();
+
+                       // DEBUG - need to know the columnSize
+                       /*
+                       foreach(DataRow schemaRow in schemaTable.Rows) {
+                               columnSize = (int) schemaRow["ColumnSize"];
+                               line.Append(columnSize.ToString());
+                               line.Append(" ");
+                       }               
+                       lineOut = line.ToString();
+                       Console.WriteLine(line);
+                       Console.WriteLine("");
+                       line = null;
+                       */
+                                                               
+                       int rows = 0;
+
+                       // column data
+                       while(reader.Read()) {
+                               rows++;
+
+                               line = new StringBuilder();
+                               for(int c = 0; c < reader.FieldCount; c++) {
+                                       int dataLen = 0;
+                                       string dataValue;
+                                       string dataType;        
+                                       DataRow row = schemaTable.Rows[c];
+                                       string colhdr = (string) row["ColumnName"];
+                                       columnSize = (int) row["ColumnSize"];
+                                       dataType = (string) row["DataType"];
+                                       if(dataType.Equals("System.Boolean")) {
+                                               columnSize = 5;
+                                       }
+                                       int columnHeaderLen = colhdr.Length;
+                                                                                               
+                                       if(reader.IsDBNull(c)) {
+                                               dataValue = "";
+                                               dataLen = 0;
+                                       }
+                                       else {
+                                               object obj = reader.GetValue(c);                                                
+                                                       
+                                               dataValue = obj.ToString();
+                                               dataLen = dataValue.Length;
+                                               line.Append(dataValue);
+                                       }
+                                       line.Append(" ");
+
+                                       // spacing
+                                       spacingChar = ' ';
+                                       if(dataLen < columnSize) {
+                                               spacing = columnSize - dataLen;
+                                               line.Append(spacingChar, spacing);
+                                       }
+                                       spacingChar = ' ';
+                                       if(columnSize < columnHeaderLen) {
+                                               spacing = columnHeaderLen - columnSize;
+                                               line.Append(spacingChar, spacing);
+                                       }
+                                               
+                               }
+                               lineOut = line.ToString();
+                               Console.WriteLine(lineOut);
+                               line = null;
+                       }
+                       Console.WriteLine("\nRows retrieved: " + rows);
+               }
+
+               public void DisplayData(IDataReader reader) {
+
+                       DataTable schemaTable;
+                       int ResultSet = 0;
+
+                       Console.WriteLine("Display any result sets...");
+
+                       do {
+                               ResultSet++;
+                               Console.WriteLine("Display the result set " + ResultSet);
+                               
+                               schemaTable = reader.GetSchemaTable();
+                               if(reader.RecordsAffected >= 0)
+                                       Console.WriteLine("SQL Command Records Affected: " + reader.RecordsAffected);
+                               else if(schemaTable == null)
+                                       Console.WriteLine("SQL Command executed.");
+                               else {
+                                       DisplayResult(reader, schemaTable);
+                               }
+                       } while(reader.NextResult());
+               }
+
+               public void RunStatement(string sql, string provider) {
+                       Console.WriteLine("Execute SQL: " + sql);
+
+                       IDbCommand cmd = null;
+                       IDataReader reader = null;
+
+                       switch(provider) {
+                       case "POSTGRESCLIENT":
+                               cmd = new SqlCommand();
+                               break;
+                       default:
+                               Console.WriteLine("Error: PostgreSQL is only supported, and it through SqlClient.");
+                               return;
+                       }
+                       cmd.CommandType = CommandType.Text;
+                       cmd.CommandText = sql;
+                       cmd.Connection = conn;
+                       try {
+                               reader = cmd.ExecuteReader();
+                               Console.WriteLine("Executed okay.");
+                               DisplayData(reader);
+                               reader.Close();
+                               reader = null;
+                               cmd = null;
+                       }
+                       catch(Exception e) {
+                               Console.WriteLine("Exception Caught Executing SQL: " + e);
+                               cmd = null;
+                       }
+               }
+
+               public void ShowHelp() {
+                       Console.WriteLine(@"Type:  \Q to quit");
+                       Console.WriteLine(@"       \ConnectionString to set the ConnectionString");
+                       Console.WriteLine(@"       \Provider to set the Provider:");
+                       Console.WriteLine(@"                 {OleDb,SqlClient,");
+                       Console.WriteLine(@"                  OracleClient,PostgresClient}");
+                       Console.WriteLine(@"       \Open to open the connection");
+                       Console.WriteLine(@"       \Close to close the connection");
+                       Console.WriteLine(@"       \Execute to execute SQL command(s)/queries(s)");
+                       Console.WriteLine(@"       \h to show this help.");
+                       Console.WriteLine("\nThe default Provider is " + provider);
+                       Console.WriteLine("\nThe default ConnectionString is: ");
+                       Console.WriteLine("    \"" + connectionString + "\"");
+                       Console.WriteLine();
+               }
+               
+               public void Run(string[] args) {
+                       string entry = "";
+                       string[] parms;
+                       StringBuilder build = null;
+
+                       Console.WriteLine("Welcome to SQL#. The interactive SQL command-line client ");
+                       Console.WriteLine("for Mono.Data.  See http://www.go-mono.com/ for more details.\n");
+                       ShowHelp();
+                       
+                       while(entry.ToUpper().Equals("\\Q") == false) {
+                               
+                               Console.Write("\nSQL# ");
+                               entry = Console.ReadLine();
+
+                               Console.WriteLine("Entered: " + entry);
+                               
+                               if(entry.Substring(0,1).Equals("\\")) {
+                                       // maybe a SQL# Command was found
+                                       parms = entry.Split(new char[1] {' '});
+                                       Console.WriteLine("Parms: " + parms.Length); 
+                                       string userCmd = parms[0].ToUpper();
+                                       switch(userCmd) {
+                                       case "\\PROVIDER":
+                                               if(parms.Length == 2) {
+                                                       string parm = parms[1].ToUpper();
+                                                       switch(parm) {
+                                                       case "OLEDB":
+                                                       case "ORACLECLIENT":
+                                                               Console.WriteLine("Error: Provider not currently supported.");
+                                                               break;
+                                                       case "SQLCLIENT":
+                                                               provider = "POSTGRESCLIENT";
+                                                               Console.WriteLine("Warning: Currently, the SqlClient provider is the PostgreSQL provider.");
+                                                               break;
+                                                       case "POSTGRESCLIENT":
+                                                               provider = parm;
+                                                               break;
+                                                       default:
+                                                               Console.WriteLine("Error: " + "Bad argument or Provider not supported.");
+                                                               break;
+                                                       }
+                                                       Console.WriteLine("Provider: " + provider);
+                                               }
+                                               else
+                                                       Console.WriteLine("Error: provider only has one parameter.");
+
+                                               break;
+                                       case "\\CONNECTIONSTRING":
+                                               if(entry.Length > 18)
+                                                       connectionString = entry.Substring(18, entry.Length - 18);
+                                               else
+                                                       connectionString = "";
+                                               Console.WriteLine("ConnectionString: " + connectionString);
+                                               Console.WriteLine("Lenght of ConnectionString: " + connectionString.Length);
+                                               break;
+                                       case "\\OPEN":
+                                               Console.WriteLine("Attempt to Open...");
+                                               switch(provider) {
+                                               case "POSTGRESCLIENT":
+                                                       conn = new SqlConnection();
+                                                       break;
+                                               default:
+                                                       Console.WriteLine("Error: Currently, PostgreSQL is the only provider supported, and it through SqlClient.");
+                                                       break;
+                                               }
+                                               conn.ConnectionString = connectionString;
+                                               try {
+                                                       conn.Open();
+                                               }
+                                               catch(Exception e) {
+                                                       Console.WriteLine("Exception Caught Opening. " + e);
+                                                       conn = null;
+                                               }
+                                               if(conn.State == ConnectionState.Open)
+                                                       Console.WriteLine("Assuming Open was successfully.");
+                                               break;
+                                       case "\\CLOSE":
+                                               Console.WriteLine("Attempt to Close...");
+                                               bool bCloseError = false;
+                                               try {
+                                                       conn.Close();
+                                               }
+                                               catch(Exception e) {
+                                                       Console.WriteLine("Exeception Caught Closing. " + e);
+                                                       bCloseError = true;
+                                               }
+                                               if(bCloseError == false)
+                                                       Console.WriteLine("Assuming Close was successfull.");
+                                               break;
+                                       case "\\EXECUTE":
+                                               if(conn == null)
+                                                       Console.WriteLine("Error: connection is not Open.");
+                                               else if(conn.State == ConnectionState.Closed)
+                                                       Console.WriteLine("Error: connection is not Open.");
+                                               else {
+                                                       if(build == null)
+                                                               Console.WriteLine("Error: SQL Buffer is empty.");
+                                                       else {
+                                                               string builtSQL = build.ToString();
+                                                               Console.WriteLine("SQL: " + builtSQL);
+
+                                                               RunStatement(builtSQL, provider);
+                                                       }
+                                                       build = null;
+                                               }
+                                               break;
+                                       case "\\H":
+                                               ShowHelp();
+                                               break;
+                                       case "\\Q":
+                                               break;
+                                       default:
+                                               Console.WriteLine("Error: Unknown user command.");
+                                               break;
+                                       }
+                               
+                               }
+                               else if(entry.IndexOf(";") >= 0) {
+                                       // most likely the end of SQL Command or Query found
+                                       // execute the SQL
+                                       if(conn == null)
+                                               Console.WriteLine("Error: connection is not Open.");
+                                       else if(conn.State == ConnectionState.Closed)
+                                               Console.WriteLine("Error: connection is not Open.");
+                                       else {
+                                               Console.WriteLine("if build == null");
+                                               if(build == null) {
+                                                       Console.WriteLine("build is null, do new");
+                                                       build = new StringBuilder();
+                                               }
+                                               Console.WriteLine("append entry");
+                                               build.Append(entry);
+                                               Console.WriteLine("build: " + build.ToString());
+                                               Console.WriteLine("RunStatement");
+                                               RunStatement(build.ToString(), provider);
+                               
+                                               build = null;
+                                       }
+                               }
+                               else {
+                                       // most likely a part of a SQL Command or Query found
+                                       // append this part of the SQL
+                                       if(build == null) {
+                                               build = new StringBuilder();
+                                       }
+                                       build.Append(entry + " ");
+                                       Console.WriteLine("build: " + build.ToString());
+                               }
+                       }                       
+               }
+       }
+
+       public class SqlSharpDriver {
+
+               public static void Main(string[] args) {
+                       SqlSharpCli sqlCommandLineEngine = new SqlSharpCli();
+                       sqlCommandLineEngine.Run(args);
+               }
+       }
+}
index bbbb9b173f9703f7e076fd3cdb8c70082d6b7371..ce77e02c53910c857da0b7271c7a370fe6d97c70 100644 (file)
@@ -26,6 +26,7 @@
                                <excludes name="TestSqlDataAdapter.cs"/>\r
                                <excludes name="PostgresTest.cs"/>\r
                                <excludes name="TestSqlParameters.cs"/>\r
+                               <excludes name="SqlSharpCli.cs"/>\r
 \r
                        </sources>\r
                        <references basedir="..\..\..\nunit">\r
@@ -50,6 +51,7 @@
                                <excludes name="PostgresTest.cs"/>\r
                                <excludes name="TestSqlDataAdapter.cs"/>\r
                                <excludes name="TestSqlParameters.cs"/>\r
+                               <excludes name="SqlSharpCli.cs"/>\r
 \r
                        </sources>\r
                        <references basedir="..\..\..\nunit">\r
index b5575cab24584dbeaac784c516b3f98cd4a0a2b5..e350a3c61c5a7d32cec98bc37b755e1ab68fea3f 100644 (file)
@@ -53,22 +53,80 @@ namespace TestSystemDataSqlClient
                                "user=postgres";
                        \r
                        try {\r
+                               string maxStrValue;\r
+\r
                                con = new SqlConnection(connectionString);\r
                                con.Open();\r
 \r
+                               // test SQL Query for an aggregate count(*)\r
                                sql =   "select count(*) " + \r
                                        "from sometable";\r
                                cmd = new SqlCommand(sql,con);\r
-                               Console.WriteLine("Executing...");\r
+                               Console.WriteLine("Executing: " + sql);\r
                                Int64 rowCount = (Int64) cmd.ExecuteScalar();\r
                                Console.WriteLine("Row Count: " + rowCount);\r
 \r
+                               // test SQL Query for an aggregate min(text)\r
                                sql =   "select max(tdesc) " + \r
                                        "from sometable";\r
                                cmd = new SqlCommand(sql,con);\r
-                               Console.WriteLine("Executing...");\r
-                               String maxValue = (string) cmd.ExecuteScalar();\r
-                               Console.WriteLine("Max Value: " + maxValue);\r
+                               Console.WriteLine("Executing: " + sql);\r
+                               string minValue = (string) cmd.ExecuteScalar();\r
+                               Console.WriteLine("Max Value: " + minValue);\r
+\r
+                               // test SQL Query for an aggregate max(text)\r
+                               sql =   "select min(tdesc) " + \r
+                                       "from sometable";\r
+                               cmd = new SqlCommand(sql,con);\r
+                               Console.WriteLine("Executing: " + sql);\r
+                               maxStrValue = (string) cmd.ExecuteScalar();\r
+                               Console.WriteLine("Max Value: " + maxStrValue);\r
+\r
+                               // test SQL Query for an aggregate max(int)\r
+                               sql =   "select min(aint4) " + \r
+                                       "from sometable";\r
+                               cmd = new SqlCommand(sql,con);\r
+                               Console.WriteLine("Executing: " + sql);\r
+                               int maxIntValue = (int) cmd.ExecuteScalar();\r
+                               Console.WriteLine("Max Value: " + maxIntValue.ToString());\r
+\r
+                               // test SQL Query for an aggregate avg(int)\r
+                               sql =   "select avg(aint4) " + \r
+                                       "from sometable";\r
+                               cmd = new SqlCommand(sql,con);\r
+                               Console.WriteLine("Executing: " + sql);\r
+                               decimal avgDecValue = (decimal) cmd.ExecuteScalar();\r
+                               Console.WriteLine("Max Value: " + avgDecValue.ToString());\r
+\r
+                               // test SQL Query for an aggregate sum(int)\r
+                               sql =   "select sum(aint4) " + \r
+                                       "from sometable";\r
+                               cmd = new SqlCommand(sql,con);\r
+                               Console.WriteLine("Executing: " + sql);\r
+                               Int64 summed = (Int64) cmd.ExecuteScalar();\r
+                               Console.WriteLine("Max Value: " + summed);\r
+\r
+                               // test a SQL Command is (INSERT, UPDATE, DELETE)\r
+                               sql =   "insert into sometable " +\r
+                                       "(tid,tdesc,aint4,atimestamp) " +\r
+                                       "values('qqq','www',234,NULL)";\r
+                               cmd = new SqlCommand(sql,con);\r
+                               Console.WriteLine("Executing: " + sql);\r
+                               object objResult1 = cmd.ExecuteScalar();\r
+                               if(objResult1 == null)\r
+                                        Console.WriteLine("Result is null. (correct)");\r
+                               else\r
+                                       Console.WriteLine("Result is not null. (not correct)");\r
+\r
+                               // test a SQL Command is not (INSERT, UPDATE, DELETE)\r
+                               sql =   "SET DATESTYLE TO 'ISO'";\r
+                               cmd = new SqlCommand(sql,con);\r
+                               Console.WriteLine("Executing: " + sql);\r
+                               object objResult2 = cmd.ExecuteScalar();\r
+                               if(objResult2 == null)\r
+                                       Console.WriteLine("Result is null. (correct)");\r
+                               else\r
+                                       Console.WriteLine("Result is not null. (not correct)");\r
 \r
                        }\r
                        catch(Exception e) {\r
index 59a2614364888009e062a5feb23f5cf94607a52f..17a61189de106af31d2ed80878f9626abec57fdf 100644 (file)
@@ -40,62 +40,91 @@ namespace TestSystemDataSqlClient {
                        Console.WriteLine("ExecuteReader...");\r
                        rdr = cmd.ExecuteReader(behavior);\r
 \r
-                       do {\r
-                               results++;\r
-                               Console.WriteLine("Result Set " + results + "...");\r
+                       if(rdr == null) {
+               
+                               Console.WriteLine("IDataReader has a Null Reference.");
+                       }
+                       else {
 \r
-                               // get the DataTable that holds\r
-                               // the schema\r
-                               DataTable dt = rdr.GetSchemaTable();\r
+                               do {\r
+                                       // get the DataTable that holds\r
+                                       // the schema\r
+                                       DataTable dt = rdr.GetSchemaTable();\r
+\r
+                                       if(rdr.RecordsAffected != -1) {\r
+                                               // Results for \r
+                                               // SQL INSERT, UPDATE, DELETE Commands \r
+                                               // have RecordsAffected >= 0\r
+                                               Console.WriteLine("Result is from a SQL Command (INSERT,UPDATE,DELETE).  Records Affected: " + rdr.RecordsAffected);\r
+                                       }\r
+                                       else if (dt == null)\r
+                                               Console.WriteLine("Result is from a SQL Command not (INSERT,UPDATE,DELETE).   Records Affected: " + rdr.RecordsAffected);\r
+                                       else {\r
+                                               // Results for\r
+                                               // SQL not INSERT, UPDATE, nor DELETE\r
+                                               // have RecordsAffected = -1\r
+                                               Console.WriteLine("Result is from a SQL SELECT Query.  Records Affected: " + rdr.RecordsAffected);\r
+                       \r
+                                               // Results for a SQL Command (CREATE TABLE, SET, etc)\r
+                                               // will have a null reference returned from GetSchemaTable()\r
+                                               // \r
+                                               // Results for a SQL SELECT Query\r
+                                               // will have a DataTable returned from GetSchemaTable()\r
+\r
+                                               results++;\r
+                                               Console.WriteLine("Result Set " + results + "...");\r
                                                \r
-                               // number of columns in the table\r
-                               Console.WriteLine("   Total Columns: " +\r
-                                       dt.Columns.Count);\r
-\r
-                               // display the schema\r
-                               foreach (DataRow schemaRow in dt.Rows) {\r
-                                       foreach (DataColumn schemaCol in dt.Columns)\r
-                                               Console.WriteLine(schemaCol.ColumnName + \r
-                                                       " = " + \r
-                                                       schemaRow[schemaCol]);\r
-                                       Console.WriteLine();\r
-                               }\r
-\r
-                               int nRows = 0;\r
-                               string output, metadataValue, dataValue;\r
-                               // Read and display the rows\r
-                               Console.WriteLine("Gonna do a Read() now...");\r
-                               while(rdr.Read()) {\r
-                                       Console.WriteLine("   Row " + nRows + ": ");\r
+                                               // number of columns in the table\r
+                                               Console.WriteLine("   Total Columns: " +\r
+                                                       dt.Columns.Count);\r
+\r
+                                               // display the schema\r
+                                               foreach (DataRow schemaRow in dt.Rows) {\r
+                                                       foreach (DataColumn schemaCol in dt.Columns)\r
+                                                               Console.WriteLine(schemaCol.ColumnName + \r
+                                                                       " = " + \r
+                                                                       schemaRow[schemaCol]);\r
+                                                       Console.WriteLine();\r
+                                               }\r
+\r
+                                               int nRows = 0;\r
+                                               string output, metadataValue, dataValue;\r
+                                               // Read and display the rows\r
+                                               Console.WriteLine("Gonna do a Read() now...");\r
+                                               while(rdr.Read()) {\r
+                                                       Console.WriteLine("   Row " + nRows + ": ");\r
                                        \r
-                                       for(c = 0; c < rdr.FieldCount; c++) {\r
-                                               // column meta data \r
-                                               DataRow dr = dt.Rows[c];\r
-                                               metadataValue = \r
-                                                       "    Col " + \r
-                                                       c + ": " + \r
-                                                       dr["ColumnName"];\r
+                                                       for(c = 0; c < rdr.FieldCount; c++) {\r
+                                                               // column meta data \r
+                                                               DataRow dr = dt.Rows[c];\r
+                                                               metadataValue = \r
+                                                                       "    Col " + \r
+                                                                       c + ": " + \r
+                                                                       dr["ColumnName"];\r
                                                \r
-                                               // column data\r
-                                               if(rdr.IsDBNull(c) == true)\r
-                                                       dataValue = " is NULL";\r
-                                               else\r
-                                                       dataValue = \r
-                                                               ": " + \r
-                                                               rdr.GetValue(c);\r
+                                                               // column data\r
+                                                               if(rdr.IsDBNull(c) == true)\r
+                                                                       dataValue = " is NULL";\r
+                                                               else\r
+                                                                       dataValue = \r
+                                                                               ": " + \r
+                                                                               rdr.GetValue(c);\r
                                        \r
-                                               // display column meta data and data\r
-                                               output = metadataValue + dataValue;                                     \r
-                                               Console.WriteLine(output);\r
-                                       }\r
-                                       nRows++;\r
-                               }\r
-                               Console.WriteLine("   Total Rows: " + \r
-                                               nRows);\r
-                       } while(rdr.NextResult());\r
-                       Console.WriteLine("Total Result sets: " + results);\r
+                                                               // display column meta data and data\r
+                                                               output = metadataValue + dataValue;                                     \r
+                                                               Console.WriteLine(output);\r
+                                                       }\r
+                                                       nRows++;\r
+                                               }\r
+                                               Console.WriteLine("   Total Rows: " + \r
+                                                       nRows);\r
+                                       }       \r
+                               } while(rdr.NextResult());\r
+                               Console.WriteLine("Total Result sets: " + results);\r
                        \r
-                       rdr.Close();\r
+                               rdr.Close();\r
+                       }\r
+                                       \r
                }\r
 \r
                [STAThread]\r
@@ -139,7 +168,13 @@ namespace TestSystemDataSqlClient {
                        sql = "version";\r
                        Test(con, sql, CommandType.StoredProcedure, \r
                                CommandBehavior.Default, "SP1");\r
-                       \r
+\r
+                       // Text - test a SQL Command (default behavior)\r
+                       // Note: this not a SQL Query\r
+                       sql = "SET DATESTYLE TO 'ISO'";\r
+                       Test(con, sql, CommandType.Text, \r
+                               CommandBehavior.Default, "TextCmd1");\r
+\r
                        con.Close();\r
                }\r
        }\r
diff --git a/mcs/tools/SqlSharp/SqlSharpCli.cs b/mcs/tools/SqlSharp/SqlSharpCli.cs
new file mode 100644 (file)
index 0000000..b221f3a
--- /dev/null
@@ -0,0 +1,363 @@
+//
+// SqlSharpCli.cs - main driver for SqlSharp
+//
+//                    Currently, only working on a command line interface for SqlSharp
+//
+//                    However, once GTK# and System.Windows.Forms are good-to-go,
+//                    I would like to create a SqlSharpGui using this.
+//
+//                    It would be nice if this is included as part of Mono
+//                    extra goodies under Mono.Data.SqlSharp.
+//
+//                    Also, this makes a good Test program for Mono System.Data.
+//                    For more information about Mono::, 
+//                    visit http://www.go-mono.com/
+//
+// Author:
+//    Daniel Morgan <danmorg@sc.rr.com>
+//
+// (C)Copyright 2002 Daniel Morgan
+//
+
+using System;
+using System.Data;
+using System.Data.Common;
+using System.Data.SqlClient;
+using System.Text;
+
+namespace Mono.Data.SqlSharp {
+       
+       // SQL Sharp - Command Line Interface
+       public class SqlSharpCli {
+       
+               private IDbConnection conn = null;
+               string provider = "POSTGRESCLIENT";
+               // string connectionString = "server=DANPC;database=pubs;uid=sa;pwd=freetds";
+               string connectionString = "host=localhost;dbname=test;user=postgres";
+
+               public void DisplayResult(IDataReader reader, DataTable schemaTable) {
+
+                       StringBuilder line = null;
+                       string lineOut;
+
+                       int spacing = 0;
+                       int columnSize = 0;
+                       
+                       char spacingChar = ' '; // a space
+                       line = new StringBuilder();
+                       Console.WriteLine("Fields in Query Result: " + reader.FieldCount);
+                       
+                       foreach(DataRow schemaRow in schemaTable.Rows) {
+                               string columnHeader = (string) schemaRow["ColumnName"];
+                               int columnHeaderSize = columnHeader.Length;
+                               line.Append(columnHeader);
+                               line.Append(" ");
+                                       
+                               // spacing
+                               columnSize = (int) schemaRow["ColumnSize"];
+                               if(columnHeaderSize < columnSize) {
+                                       spacing = columnSize - columnHeaderSize;
+                                       line.Append(spacingChar, spacing);
+                               }
+
+                       }
+                       lineOut = line.ToString();
+                       Console.WriteLine(line);
+                       line = null;
+                       line = new StringBuilder();
+
+                       // DEBUG - need to know the columnSize
+                       /*
+                       foreach(DataRow schemaRow in schemaTable.Rows) {
+                               columnSize = (int) schemaRow["ColumnSize"];
+                               line.Append(columnSize.ToString());
+                               line.Append(" ");
+                       }               
+                       lineOut = line.ToString();
+                       Console.WriteLine(line);
+                       Console.WriteLine("");
+                       line = null;
+                       */
+                                                               
+                       int rows = 0;
+
+                       // column data
+                       while(reader.Read()) {
+                               rows++;
+
+                               line = new StringBuilder();
+                               for(int c = 0; c < reader.FieldCount; c++) {
+                                       int dataLen = 0;
+                                       string dataValue;
+                                       string dataType;        
+                                       DataRow row = schemaTable.Rows[c];
+                                       string colhdr = (string) row["ColumnName"];
+                                       columnSize = (int) row["ColumnSize"];
+                                       dataType = (string) row["DataType"];
+                                       if(dataType.Equals("System.Boolean")) {
+                                               columnSize = 5;
+                                       }
+                                       int columnHeaderLen = colhdr.Length;
+                                                                                               
+                                       if(reader.IsDBNull(c)) {
+                                               dataValue = "";
+                                               dataLen = 0;
+                                       }
+                                       else {
+                                               object obj = reader.GetValue(c);                                                
+                                                       
+                                               dataValue = obj.ToString();
+                                               dataLen = dataValue.Length;
+                                               line.Append(dataValue);
+                                       }
+                                       line.Append(" ");
+
+                                       // spacing
+                                       spacingChar = ' ';
+                                       if(dataLen < columnSize) {
+                                               spacing = columnSize - dataLen;
+                                               line.Append(spacingChar, spacing);
+                                       }
+                                       spacingChar = ' ';
+                                       if(columnSize < columnHeaderLen) {
+                                               spacing = columnHeaderLen - columnSize;
+                                               line.Append(spacingChar, spacing);
+                                       }
+                                               
+                               }
+                               lineOut = line.ToString();
+                               Console.WriteLine(lineOut);
+                               line = null;
+                       }
+                       Console.WriteLine("\nRows retrieved: " + rows);
+               }
+
+               public void DisplayData(IDataReader reader) {
+
+                       DataTable schemaTable;
+                       int ResultSet = 0;
+
+                       Console.WriteLine("Display any result sets...");
+
+                       do {
+                               ResultSet++;
+                               Console.WriteLine("Display the result set " + ResultSet);
+                               
+                               schemaTable = reader.GetSchemaTable();
+                               if(reader.RecordsAffected >= 0)
+                                       Console.WriteLine("SQL Command Records Affected: " + reader.RecordsAffected);
+                               else if(schemaTable == null)
+                                       Console.WriteLine("SQL Command executed.");
+                               else {
+                                       DisplayResult(reader, schemaTable);
+                               }
+                       } while(reader.NextResult());
+               }
+
+               public void RunStatement(string sql, string provider) {
+                       Console.WriteLine("Execute SQL: " + sql);
+
+                       IDbCommand cmd = null;
+                       IDataReader reader = null;
+
+                       switch(provider) {
+                       case "POSTGRESCLIENT":
+                               cmd = new SqlCommand();
+                               break;
+                       default:
+                               Console.WriteLine("Error: PostgreSQL is only supported, and it through SqlClient.");
+                               return;
+                       }
+                       cmd.CommandType = CommandType.Text;
+                       cmd.CommandText = sql;
+                       cmd.Connection = conn;
+                       try {
+                               reader = cmd.ExecuteReader();
+                               Console.WriteLine("Executed okay.");
+                               DisplayData(reader);
+                               reader.Close();
+                               reader = null;
+                               cmd = null;
+                       }
+                       catch(Exception e) {
+                               Console.WriteLine("Exception Caught Executing SQL: " + e);
+                               cmd = null;
+                       }
+               }
+
+               public void ShowHelp() {
+                       Console.WriteLine(@"Type:  \Q to quit");
+                       Console.WriteLine(@"       \ConnectionString to set the ConnectionString");
+                       Console.WriteLine(@"       \Provider to set the Provider:");
+                       Console.WriteLine(@"                 {OleDb,SqlClient,");
+                       Console.WriteLine(@"                  OracleClient,PostgresClient}");
+                       Console.WriteLine(@"       \Open to open the connection");
+                       Console.WriteLine(@"       \Close to close the connection");
+                       Console.WriteLine(@"       \Execute to execute SQL command(s)/queries(s)");
+                       Console.WriteLine(@"       \h to show this help.");
+                       Console.WriteLine("\nThe default Provider is " + provider);
+                       Console.WriteLine("\nThe default ConnectionString is: ");
+                       Console.WriteLine("    \"" + connectionString + "\"");
+                       Console.WriteLine();
+               }
+               
+               public void Run(string[] args) {
+                       string entry = "";
+                       string[] parms;
+                       StringBuilder build = null;
+
+                       Console.WriteLine("Welcome to SQL#. The interactive SQL command-line client ");
+                       Console.WriteLine("for Mono.Data.  See http://www.go-mono.com/ for more details.\n");
+                       ShowHelp();
+                       
+                       while(entry.ToUpper().Equals("\\Q") == false) {
+                               
+                               Console.Write("\nSQL# ");
+                               entry = Console.ReadLine();
+
+                               Console.WriteLine("Entered: " + entry);
+                               
+                               if(entry.Substring(0,1).Equals("\\")) {
+                                       // maybe a SQL# Command was found
+                                       parms = entry.Split(new char[1] {' '});
+                                       Console.WriteLine("Parms: " + parms.Length); 
+                                       string userCmd = parms[0].ToUpper();
+                                       switch(userCmd) {
+                                       case "\\PROVIDER":
+                                               if(parms.Length == 2) {
+                                                       string parm = parms[1].ToUpper();
+                                                       switch(parm) {
+                                                       case "OLEDB":
+                                                       case "ORACLECLIENT":
+                                                               Console.WriteLine("Error: Provider not currently supported.");
+                                                               break;
+                                                       case "SQLCLIENT":
+                                                               provider = "POSTGRESCLIENT";
+                                                               Console.WriteLine("Warning: Currently, the SqlClient provider is the PostgreSQL provider.");
+                                                               break;
+                                                       case "POSTGRESCLIENT":
+                                                               provider = parm;
+                                                               break;
+                                                       default:
+                                                               Console.WriteLine("Error: " + "Bad argument or Provider not supported.");
+                                                               break;
+                                                       }
+                                                       Console.WriteLine("Provider: " + provider);
+                                               }
+                                               else
+                                                       Console.WriteLine("Error: provider only has one parameter.");
+
+                                               break;
+                                       case "\\CONNECTIONSTRING":
+                                               if(entry.Length > 18)
+                                                       connectionString = entry.Substring(18, entry.Length - 18);
+                                               else
+                                                       connectionString = "";
+                                               Console.WriteLine("ConnectionString: " + connectionString);
+                                               Console.WriteLine("Lenght of ConnectionString: " + connectionString.Length);
+                                               break;
+                                       case "\\OPEN":
+                                               Console.WriteLine("Attempt to Open...");
+                                               switch(provider) {
+                                               case "POSTGRESCLIENT":
+                                                       conn = new SqlConnection();
+                                                       break;
+                                               default:
+                                                       Console.WriteLine("Error: Currently, PostgreSQL is the only provider supported, and it through SqlClient.");
+                                                       break;
+                                               }
+                                               conn.ConnectionString = connectionString;
+                                               try {
+                                                       conn.Open();
+                                               }
+                                               catch(Exception e) {
+                                                       Console.WriteLine("Exception Caught Opening. " + e);
+                                                       conn = null;
+                                               }
+                                               if(conn.State == ConnectionState.Open)
+                                                       Console.WriteLine("Assuming Open was successfully.");
+                                               break;
+                                       case "\\CLOSE":
+                                               Console.WriteLine("Attempt to Close...");
+                                               bool bCloseError = false;
+                                               try {
+                                                       conn.Close();
+                                               }
+                                               catch(Exception e) {
+                                                       Console.WriteLine("Exeception Caught Closing. " + e);
+                                                       bCloseError = true;
+                                               }
+                                               if(bCloseError == false)
+                                                       Console.WriteLine("Assuming Close was successfull.");
+                                               break;
+                                       case "\\EXECUTE":
+                                               if(conn == null)
+                                                       Console.WriteLine("Error: connection is not Open.");
+                                               else if(conn.State == ConnectionState.Closed)
+                                                       Console.WriteLine("Error: connection is not Open.");
+                                               else {
+                                                       if(build == null)
+                                                               Console.WriteLine("Error: SQL Buffer is empty.");
+                                                       else {
+                                                               string builtSQL = build.ToString();
+                                                               Console.WriteLine("SQL: " + builtSQL);
+
+                                                               RunStatement(builtSQL, provider);
+                                                       }
+                                                       build = null;
+                                               }
+                                               break;
+                                       case "\\H":
+                                               ShowHelp();
+                                               break;
+                                       case "\\Q":
+                                               break;
+                                       default:
+                                               Console.WriteLine("Error: Unknown user command.");
+                                               break;
+                                       }
+                               
+                               }
+                               else if(entry.IndexOf(";") >= 0) {
+                                       // most likely the end of SQL Command or Query found
+                                       // execute the SQL
+                                       if(conn == null)
+                                               Console.WriteLine("Error: connection is not Open.");
+                                       else if(conn.State == ConnectionState.Closed)
+                                               Console.WriteLine("Error: connection is not Open.");
+                                       else {
+                                               Console.WriteLine("if build == null");
+                                               if(build == null) {
+                                                       Console.WriteLine("build is null, do new");
+                                                       build = new StringBuilder();
+                                               }
+                                               Console.WriteLine("append entry");
+                                               build.Append(entry);
+                                               Console.WriteLine("build: " + build.ToString());
+                                               Console.WriteLine("RunStatement");
+                                               RunStatement(build.ToString(), provider);
+                               
+                                               build = null;
+                                       }
+                               }
+                               else {
+                                       // most likely a part of a SQL Command or Query found
+                                       // append this part of the SQL
+                                       if(build == null) {
+                                               build = new StringBuilder();
+                                       }
+                                       build.Append(entry + " ");
+                                       Console.WriteLine("build: " + build.ToString());
+                               }
+                       }                       
+               }
+       }
+
+       public class SqlSharpDriver {
+
+               public static void Main(string[] args) {
+                       SqlSharpCli sqlCommandLineEngine = new SqlSharpCli();
+                       sqlCommandLineEngine.Run(args);
+               }
+       }
+}