Author: fxjr
Date: 2005-07-05 18:55:29 -0400 (Tue, 05 Jul 2005)
New Revision: 46979

Modified:
   trunk/mcs/class/Npgsql/ChangeLog
   trunk/mcs/class/Npgsql/Npgsql/NpgsqlClosedState.cs
   trunk/mcs/class/Npgsql/Npgsql/NpgsqlCommand.cs
   trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnection.cs
   trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnectionString.cs
   trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnector.cs
   trunk/mcs/class/Npgsql/Npgsql/NpgsqlDataReader.cs
   trunk/mcs/class/Npgsql/Npgsql/NpgsqlException.cs
   trunk/mcs/class/Npgsql/Npgsql/NpgsqlParameter.cs
   trunk/mcs/class/Npgsql/Npgsql/NpgsqlParameterCollection.cs
   trunk/mcs/class/Npgsql/Npgsql/NpgsqlState.resx
   trunk/mcs/class/Npgsql/NpgsqlTypes/NpgsqlDbType.cs
   trunk/mcs/class/Npgsql/NpgsqlTypes/NpgsqlTypesHelper.cs
Log:
2005-07-05 Francisco Figueiredo Jr.  <[EMAIL PROTECTED]>
   
       * NpgsqlTypes/NpgsqlDbType.cs,
         NpgsqlTypes/NpgsqlTypesHelper.cs,
         Npgsql/NpgsqlParameter.cs,
         Npgsql/NpgsqlConnectionString.cs,
         Npgsql/NpgsqlState.resx,
         Npgsql/NpgsqlConnection.cs,
         Npgsql/NpgsqlClosedState.cs,
         Npgsql/NpgsqlCommand.cs,
         Npgsql/NpgsqlConnector.cs,
         Npgsql/NpgsqlParameterCollection.cs,
         Npgsql/NpgsqlDataReader.cs,
         Npgsql/NpgsqlException.cs: Updated to Npgsql 0.7beta6 gborg code.




Modified: trunk/mcs/class/Npgsql/ChangeLog
===================================================================
--- trunk/mcs/class/Npgsql/ChangeLog    2005-07-05 22:53:57 UTC (rev 46978)
+++ trunk/mcs/class/Npgsql/ChangeLog    2005-07-05 22:55:29 UTC (rev 46979)
@@ -1,7 +1,23 @@
 
+
+2005-07-05 Francisco Figueiredo Jr.  <[EMAIL PROTECTED]>
+   
+    * NpgsqlTypes/NpgsqlDbType.cs,
+      NpgsqlTypes/NpgsqlTypesHelper.cs,
+      Npgsql/NpgsqlParameter.cs,
+      Npgsql/NpgsqlConnectionString.cs,
+      Npgsql/NpgsqlState.resx,
+      Npgsql/NpgsqlConnection.cs,
+      Npgsql/NpgsqlClosedState.cs,
+      Npgsql/NpgsqlCommand.cs,
+      Npgsql/NpgsqlConnector.cs,
+      Npgsql/NpgsqlParameterCollection.cs,
+      Npgsql/NpgsqlDataReader.cs,
+      Npgsql/NpgsqlException.cs: Updated to Npgsql 0.7beta6 gborg code.
+
 2005-02-20 Francisco Figueiredo Jr.  <[EMAIL PROTECTED]>
 
-   * Npgsql/NpgsqlCommand.cs: Fixed a problem when using prepare commands 
inside a transaction. Portal wasn't being released. We use the unnamed portal 
now. Thanks Marcin (marcin at floryan dot neostrada dot pl) for the heads up.
+    * Npgsql/NpgsqlCommand.cs: Fixed a problem when using prepare commands 
inside a transaction. Portal wasn't being released. We use the unnamed portal 
now. Thanks Marcin (marcin at floryan dot neostrada dot pl) for the heads up.
 
 2005-02-13 Francisco Figueiredo Jr.  <[EMAIL PROTECTED]>
 

Modified: trunk/mcs/class/Npgsql/Npgsql/NpgsqlClosedState.cs
===================================================================
--- trunk/mcs/class/Npgsql/Npgsql/NpgsqlClosedState.cs  2005-07-05 22:53:57 UTC 
(rev 46978)
+++ trunk/mcs/class/Npgsql/Npgsql/NpgsqlClosedState.cs  2005-07-05 22:55:29 UTC 
(rev 46979)
@@ -78,38 +78,53 @@
 
         public override void Open(NpgsqlConnector context)
         {
-            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Open");
-
-            TcpClient tcpc = new TcpClient();
-            tcpc.Connect(new IPEndPoint(ResolveIPHost(context.Host), 
context.Port));
-            Stream stream = tcpc.GetStream();
-
-            // If the PostgreSQL server has SSL connectors enabled Open 
SslClientStream if (response == 'S') {
-            if (context.SSL)
+            
+            try
             {
-                PGUtil.WriteInt32(stream, 8);
-                PGUtil.WriteInt32(stream,80877103);
-                // Receive response
-                Char response = (Char)stream.ReadByte();
-                if (response == 'S')
+                NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, 
"Open");
+    
+                TcpClient tcpc = new TcpClient();
+                tcpc.Connect(new IPEndPoint(ResolveIPHost(context.Host), 
context.Port));
+                Stream stream = tcpc.GetStream();
+    
+                               
+                // If the PostgreSQL server has SSL connectors enabled Open 
SslClientStream if (response == 'S') {
+                if (context.SSL || (context.SslMode == SslMode.Require) || 
(context.SslMode == SslMode.Prefer))
                 {
-                    stream = new SslClientStream(
-                                 tcpc.GetStream(),
-                                 context.Host,
-                                 true,
-                                 
Mono.Security.Protocol.Tls.SecurityProtocolType.Default
-                             );
-
-                    ((SslClientStream)stream).ClientCertSelectionDelegate = 
new CertificateSelectionCallback(context.DefaultCertificateSelectionCallback);
-                    ((SslClientStream)stream).ServerCertValidationDelegate = 
new CertificateValidationCallback(context.DefaultCertificateValidationCallback);
-                    ((SslClientStream)stream).PrivateKeyCertSelectionDelegate 
= new PrivateKeySelectionCallback(context.DefaultPrivateKeySelectionCallback);
+                    PGUtil.WriteInt32(stream, 8);
+                    PGUtil.WriteInt32(stream,80877103);
+                    // Receive response
+                    
+                    Char response = (Char)stream.ReadByte();
+                    if (response == 'S')
+                    {
+                        stream = new SslClientStream(
+                                    tcpc.GetStream(),
+                                    context.Host,
+                                    true,
+                                    
Mono.Security.Protocol.Tls.SecurityProtocolType.Default
+                                );
+    
+                        ((SslClientStream)stream).ClientCertSelectionDelegate 
= new CertificateSelectionCallback(context.DefaultCertificateSelectionCallback);
+                        ((SslClientStream)stream).ServerCertValidationDelegate 
= new 
CertificateValidationCallback(context.DefaultCertificateValidationCallback);
+                        
((SslClientStream)stream).PrivateKeyCertSelectionDelegate = new 
PrivateKeySelectionCallback(context.DefaultPrivateKeySelectionCallback);
+                    }
+                    else if (context.SslMode == SslMode.Require)
+                        throw new 
InvalidOperationException(resman.GetString("Exception_Ssl_RequestError"));
+                    
                 }
+    
+                context.Stream = stream;
+    
+                NpgsqlEventLog.LogMsg(resman, "Log_ConnectedTo", 
LogLevel.Normal, context.Host, context.Port);
+                ChangeState(context, NpgsqlConnectedState.Instance);
+                
+                
             }
-
-            context.Stream = stream;
-
-            NpgsqlEventLog.LogMsg(resman, "Log_ConnectedTo", LogLevel.Normal, 
context.Host, context.Port);
-            ChangeState(context, NpgsqlConnectedState.Instance);
+            catch (Exception e)
+            {
+                throw new NpgsqlException(e.ToString(), e);
+            }
         }
 
     }

Modified: trunk/mcs/class/Npgsql/Npgsql/NpgsqlCommand.cs
===================================================================
--- trunk/mcs/class/Npgsql/Npgsql/NpgsqlCommand.cs      2005-07-05 22:53:57 UTC 
(rev 46978)
+++ trunk/mcs/class/Npgsql/Npgsql/NpgsqlCommand.cs      2005-07-05 22:55:29 UTC 
(rev 46979)
@@ -32,6 +32,8 @@
 
 using NpgsqlTypes;
 
+using System.Text.RegularExpressions;
+
 #if WITHDESIGN
 using Npgsql.Design;
 #endif
@@ -100,6 +102,7 @@
             planName = String.Empty;
             text = cmdText;
             this.connection = connection;
+            
             if (this.connection != null)
                 this.connector = connection.Connector;
 
@@ -119,6 +122,7 @@
         {
             resman = new System.Resources.ResourceManager(this.GetType());
             NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, 
CLASSNAME);
+            
 
             planName = String.Empty;
             text = cmdText;
@@ -579,9 +583,9 @@
             ExecuteCommand();
             
             UpdateOutputParameters();
-
+            
             // Get the resultsets and create a Datareader with them.
-            return new NpgsqlDataReader(Connector.Mediator.ResultSets, 
Connector.Mediator.CompletedResponses, connection, cb);
+            return new NpgsqlDataReader(Connector.Mediator.ResultSets, 
Connector.Mediator.CompletedResponses, cb, this);
         }
 
         ///<summary>
@@ -797,41 +801,86 @@
                 result = AddSingleRowBehaviorSupport(result);
                                            
                 return result;
-             }   
+            }   
 
-
-            //CheckParameters();
-
-            for (Int32 i = 0; i < parameters.Count; i++)
+             
+            // Get parameters in query string to translate them to their 
actual values.
+             
+            // This regular expression gets all the parameters in format 
:param or @param 
+            // and everythingelse.
+            // This is only needed if query string has parameters. Else, just 
append the
+            // parameter values in order they were put in parameter collection.
+            
+            
+            // If parenthesis don't need to be added, they were added by user 
with parameter names. Replace them.
+            if (!addProcedureParenthesis)
             {
-                NpgsqlParameter Param = parameters[i];
-
+            
+                Regex a = new Regex(@"(:[\w]*)|(@[\w]*)|(.)");
                 
-                if ((Param.Direction == ParameterDirection.Input) ||
-                    (Param.Direction == ParameterDirection.InputOutput))
+                //CheckParameters();
+    
+                StringBuilder sb = new StringBuilder();
                 
+                for ( Match m = a.Match(result); m.Success; m = m.NextMatch() )
+                {
+                    String s = m.Groups[0].ToString();
                     
-                    // If parenthesis don't need to be added, they were added 
by user with parameter names. Replace them.
-                    if (!addProcedureParenthesis)
-                        // FIXME DEBUG ONLY
-                        // adding the '::<datatype>' on the end of a parameter 
is a highly
-                        // questionable practice, but it is great for 
debugging!
-                        // Removed as this was going in infinite loop when the 
parameter name had the same name of parameter
-                        // type name. i.e.: parameter name called :text of 
type text. It would conflict with the parameter type name ::text.
-                        result = ReplaceParameterValue(
-                                    result,
-                                    Param.ParameterName,
-                                    
Param.TypeInfo.ConvertToBackend(Param.Value, false)
-                                );
-                    else
-                        result += Param.TypeInfo.ConvertToBackend(Param.Value, 
false) + ",";
+                    if ((s.StartsWith(":") ||
+                        s.StartsWith("@")) &&
+                       Parameters.Contains(s))
+                    {
+                        // It's a parameter. Lets handle it.
+                    
+                        NpgsqlParameter p = Parameters[s];
+                        if ((p.Direction == ParameterDirection.Input) ||
+                        (p.Direction == ParameterDirection.InputOutput))
+                       {
+                            
+                            // FIXME DEBUG ONLY
+                            // adding the '::<datatype>' on the end of a 
parameter is a highly
+                            // questionable practice, but it is great for 
debugging!
+                            sb.Append(p.TypeInfo.ConvertToBackend(p.Value, 
false));
+                           
+                           // Only add data type info if we are calling an 
stored procedure
+                                                               
+                            if (type == CommandType.StoredProcedure)
+                            {
+                                sb.Append("::");
+                               sb.Append(p.TypeInfo.Name);
+                               if (p.TypeInfo.UseSize && (p.Size > 0))
+                                   sb.Append("(").Append(p.Size).Append(")");
+                           }
+                        }   
+                    }   
+                    else 
+                        sb.Append(s);
+                    
+                }
+                
+                result = sb.ToString();
             }
+                
+                
+            else
+            {
+                
+                
+                for (Int32 i = 0; i < parameters.Count; i++)
+                {
+                    NpgsqlParameter Param = parameters[i];
+    
+                    
+                    if ((Param.Direction == ParameterDirection.Input) ||
+                        (Param.Direction == ParameterDirection.InputOutput))
+                    
+                        
+                            result += 
Param.TypeInfo.ConvertToBackend(Param.Value, false) + "::" + 
Param.TypeInfo.Name + ",";
+                }
             
             
-            if (addProcedureParenthesis)
-            {
                 // Remove a trailing comma added from parameter handling 
above. If any.
-                // Maybe there are only output parameters.
+                // Maybe there are only output parameters. If so, there will 
be no comma.
                 if (result.EndsWith(","))
                     result = result.Remove(result.Length - 1, 1);
                 
@@ -1087,14 +1136,7 @@
 
             while(paramStart > -1)
             {
-                if((resLen > paramEnd) &&
-                        (result[paramEnd] == ' ' ||
-                         result[paramEnd] == ',' ||
-                         result[paramEnd] == ')' ||
-                         result[paramEnd] == ';' ||
-                         result[paramEnd] == '\n' ||
-                         result[paramEnd] == '\r' ||
-                         result[paramEnd] == '\t'))
+                if((resLen > paramEnd) && !Char.IsLetterOrDigit(result, 
paramEnd))
                 {
                     result = result.Substring(0, paramStart) + paramVal + 
result.Substring(paramEnd);
                     found = true;
@@ -1179,5 +1221,9 @@
                 }
             }
         }
+        
+        
+         
+        
     }
 }

Modified: trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnection.cs
===================================================================
--- trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnection.cs   2005-07-05 22:53:57 UTC 
(rev 46978)
+++ trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnection.cs   2005-07-05 22:55:29 UTC 
(rev 46979)
@@ -722,7 +722,84 @@
                 throw new ObjectDisposedException(CLASSNAME);
             }
         }
+        
+        
+        /// <summary>
+        /// This method returns the collections we support.
+        /// <summary>
+        public DataTable GetSchema()
+        {
+            
+            
+            DataTable result = new DataTable("Schema");
+            
+            result.Columns.Add ("CollectionName", typeof (string));
+            result.Columns.Add ("NumberOfRestrictions", typeof (int));
+            
+            
+            DataRow row = result.NewRow();
+            row["CollectionName"] = "Databases";
+            row["NumberOfRestrictions"] = 0;
+            
+            result.Rows.Add(row);
+            
+            return result;
+        }
+        
+        /// <summary>
+        /// This method returns the collection data.
+        ///
+        /// <summary>
+        public DataTable GetSchema(String CollectionName)
+        {
+           
+            if (CollectionName == "Databases")
+                return GetSchemaDatabases();
+            
+            throw new NotSupportedException(); 
+            
+        }
+        
+        
+        private DataTable GetSchemaDatabases()
+        {
+            NpgsqlConnection conn = new 
NpgsqlConnection(this.ConnectionString);
+            conn.Open();
+            NpgsqlCommand c = new NpgsqlCommand("SELECT d.datname as \"Name\", 
u.usename as \"Owner\", pg_catalog.pg_encoding_to_char(d.encoding) as 
\"Encoding\" FROM pg_catalog.pg_database d LEFT JOIN pg_catalog.pg_user u ON 
d.datdba = u.usesysid ORDER BY 1;", conn);
+            
+            
+            DataTable result = new DataTable("Databases");
+            
+            result.Columns.Add ("Name", typeof (string));
+            result.Columns.Add ("Owner", typeof (string));
+            result.Columns.Add ("Encoding", typeof (string));
+            
+            
+            NpgsqlDataReader dr = c.ExecuteReader();
+                        
+            while (dr.Read())
+            {
+                        
+                DataRow row = result.NewRow();
+                row["Name"] = dr["Name"];
+                row["Owner"] = dr["Owner"];
+                row["Encoding"] = dr["Encoding"];
+                
+                result.Rows.Add(row);
+            }
+            
+            
+            dr.Close();
+            
+            conn.Close();
+            
 
+            return result;
+        }
+        
+        
+        
+
     }
 
 

Modified: trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnectionString.cs
===================================================================
--- trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnectionString.cs     2005-07-05 
22:53:57 UTC (rev 46978)
+++ trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnectionString.cs     2005-07-05 
22:55:29 UTC (rev 46979)
@@ -347,6 +347,27 @@
 
             }
         }
+        
+        public SslMode ToSslMode(String Key)
+        {
+            return ToSslMode(Key, SslMode.Disable);
+        }
+        
+        ///<summary>
+        ///</summary>
+        
+        public SslMode ToSslMode(String Key, SslMode Default)
+        {
+            if (! connection_string_values.Contains(Key))
+            {
+                return Default;
+            }
+            
+            return (SslMode)Enum.Parse(typeof(SslMode), ToString(Key), true);
+        }
+
+
+        
     }
 
 
@@ -362,6 +383,7 @@
         public static readonly String UserName         = "USER ID";
         public static readonly String Password         = "PASSWORD";
         public static readonly String SSL              = "SSL";
+        public static readonly String SslMode          = "SSLMODE";
         public static readonly String Encoding         = "ENCODING";
         public static readonly String Timeout          = "TIMEOUT";
 
@@ -416,4 +438,15 @@
         public static readonly Int32 MaxPoolSize       = 20;
         public static readonly Int32 Timeout           = 15; // Seconds
     }
+    
+    internal enum SslMode
+    {
+        Disable = 1 << 0,
+        Allow =   1 << 1,
+        Prefer =  1 << 2,
+        Require = 1 << 3
+    }
+
+
+
 }

Modified: trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnector.cs
===================================================================
--- trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnector.cs    2005-07-05 22:53:57 UTC 
(rev 46978)
+++ trunk/mcs/class/Npgsql/Npgsql/NpgsqlConnector.cs    2005-07-05 22:55:29 UTC 
(rev 46979)
@@ -182,6 +182,16 @@
                 return ConnectionString.ToBool(ConnectionStringKeys.SSL);
             }
         }
+        
+        internal SslMode SslMode
+        {
+            get
+            {
+                return 
ConnectionString.ToSslMode(ConnectionStringKeys.SslMode);
+            }
+        }
+        
+        
 
         /// <summary>
         /// Gets the current state of the connection.

Modified: trunk/mcs/class/Npgsql/Npgsql/NpgsqlDataReader.cs
===================================================================
--- trunk/mcs/class/Npgsql/Npgsql/NpgsqlDataReader.cs   2005-07-05 22:53:57 UTC 
(rev 46978)
+++ trunk/mcs/class/Npgsql/Npgsql/NpgsqlDataReader.cs   2005-07-05 22:55:29 UTC 
(rev 46979)
@@ -45,16 +45,17 @@
         private DataTable                      _currentResultsetSchema;
         private CommandBehavior     _behavior;
         private Boolean             _isClosed;
+        private NpgsqlCommand       _command;
 
 
         // Logging related values
         private static readonly String CLASSNAME = "NpgsqlDataReader";
 
-        internal NpgsqlDataReader( ArrayList resultsets, ArrayList responses, 
NpgsqlConnection connection, CommandBehavior behavior)
+        internal NpgsqlDataReader( ArrayList resultsets, ArrayList responses, 
CommandBehavior behavior, NpgsqlCommand command)
         {
             _resultsets = resultsets;
             _responses = responses;
-            _connection = connection;
+            _connection = command.Connection;
             _rowIndex = -1;
             _resultsetIndex = 0;
 
@@ -63,6 +64,7 @@
 
             _behavior = behavior;
             _isClosed = false;
+            _command = command;
         }
 
         private Boolean HaveResultSet()
@@ -177,7 +179,7 @@
         {
             get
             {
-                return _currentResultset.Count > 0;
+               return (HaveResultSet() ? _currentResultset.Count > 0 : false);
             }
 
         }
@@ -223,10 +225,10 @@
         public Boolean Read()
         {
             NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Read");
-
+           
             if (!HaveResultSet())
                return false;
-
+               
             if (_rowIndex < _currentResultset.Count)
             {
                 _rowIndex++;
@@ -236,6 +238,8 @@
             {
                 return false;
             }
+
+
         }
 
         /// <summary>
@@ -646,7 +650,15 @@
             NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, 
"GetResultsetSchema");
             DataTable result = null;
 
+
             NpgsqlRowDescription rd = _currentResultset.RowDescription;
+
+
+            ArrayList list = null;
+
+            list = GetPrimaryKeys(GetTableNameFromQuery());
+
+
             Int16 numFields = rd.NumFields;
             if(numFields > 0)
             {
@@ -659,8 +671,6 @@
                 result.Columns.Add ("NumericScale", typeof (int));
                 result.Columns.Add ("IsUnique", typeof (bool));
                 result.Columns.Add ("IsKey", typeof (bool));
-                DataColumn dc = result.Columns["IsKey"];
-                dc.AllowDBNull = true; // IsKey can have a DBNull
                 result.Columns.Add ("BaseCatalogName", typeof (string));
                 result.Columns.Add ("BaseColumnName", typeof (string));
                 result.Columns.Add ("BaseSchemaName", typeof (string));
@@ -679,6 +689,10 @@
 
                 DataRow row;
 
+
+
+
+
                 for (Int16 i = 0; i < numFields; i++)
                 {
                     row = result.NewRow();
@@ -689,13 +703,13 @@
                     row["NumericPrecision"] = 0;
                     row["NumericScale"] = 0;
                     row["IsUnique"] = false;
-                    row["IsKey"] = DBNull.Value;
+                    row["IsKey"] = IsKey(GetName(i), list);
                     row["BaseCatalogName"] = "";
                     row["BaseColumnName"] = GetName(i);
                     row["BaseSchemaName"] = "";
                     row["BaseTableName"] = "";
                     row["DataType"] = GetFieldType(i);
-                    row["AllowDBNull"] = false;
+                    row["AllowDBNull"] = IsNullable(i);
                     row["ProviderType"] = (int) rd[i].type_oid;
                     row["IsAliased"] = false;
                     row["IsExpression"] = false;
@@ -708,12 +722,94 @@
 
                     result.Rows.Add(row);
                 }
+
+
+
+
+
             }
 
             return result;
 
         }
 
+
+        private Boolean IsKey(String ColumnName, ArrayList ListOfKeys)
+        {
+            if (ListOfKeys == null || ListOfKeys.Count == 0)
+                return false;
+
+            foreach(String s in ListOfKeys)
+            {
+
+                if (s == ColumnName)
+                    return true;
+            }
+
+            return false;
+        }
+
+        private ArrayList GetPrimaryKeys(String tablename)
+        {
+
+            if (tablename == String.Empty)
+                return null;
+
+            String getPKColumns = "select a.attname from pg_catalog.pg_class 
ct, pg_catalog.pg_class ci, pg_catalog.pg_attribute a, pg_catalog.pg_index i  
WHERE ct.oid=i.indrelid AND ci.oid=i.indexrelid  AND a.attrelid=ci.oid AND 
i.indisprimary AND ct.relname = :tablename";
+
+            ArrayList result = new ArrayList();
+            NpgsqlConnection metadataConn = _connection.Clone();
+
+            NpgsqlCommand c = new NpgsqlCommand(getPKColumns, metadataConn);
+            c.Parameters.Add(new NpgsqlParameter("tablename", 
NpgsqlDbType.Text));
+            c.Parameters["tablename"].Value = tablename;
+
+
+            NpgsqlDataReader dr = c.ExecuteReader();
+
+
+            while (dr.Read())
+                result.Add(dr[0]);
+
+
+            metadataConn.Close();
+
+            return result;
+        }
+
+
+
+        private Boolean IsNullable(Int32 FieldIndex)
+        {
+            return true;
+        }
+
+
+        ///<summary>
+        /// This methods parses the command text and tries to get the tablename
+        /// from it.
+        ///</summary>
+        private String GetTableNameFromQuery()
+        {
+            Int32 fromClauseIndex = 
_command.CommandText.ToLower().IndexOf("from");
+
+            String tableName = _command.CommandText.Substring(fromClauseIndex 
+ 4).Trim();
+
+            if (tableName == String.Empty)
+                return String.Empty;
+
+            /*if (tableName.EndsWith("."));
+                return String.Empty;
+              */
+            foreach (Char c in tableName.Substring (0, tableName.Length - 1))
+            if (!Char.IsLetterOrDigit (c) && c != '_' && c != '.')
+                return String.Empty;
+
+
+            return tableName;
+
+        }
+
         IEnumerator IEnumerable.GetEnumerator ()
         {
             return new System.Data.Common.DbEnumerator (this);

Modified: trunk/mcs/class/Npgsql/Npgsql/NpgsqlException.cs
===================================================================
--- trunk/mcs/class/Npgsql/Npgsql/NpgsqlException.cs    2005-07-05 22:53:57 UTC 
(rev 46978)
+++ trunk/mcs/class/Npgsql/Npgsql/NpgsqlException.cs    2005-07-05 22:55:29 UTC 
(rev 46979)
@@ -46,7 +46,9 @@
 
         // To allow deserialization.
         private NpgsqlException(SerializationInfo info, StreamingContext 
context) : base(info, context)
-        {}
+        {
+            errors = (IList)info.GetValue("errors", typeof(IList));
+        }
 
         /// <summary>
         /// Construct a backend error exception based on a list of one or more
@@ -59,6 +61,27 @@
             this.errors = errors;
 
         }
+        
+        
+        internal NpgsqlException(String message) : base (message)
+        {}
+        
+        internal NpgsqlException(String message, Exception innerException) : 
base (message, innerException)
+        {}
+        
+        
+        override public void GetObjectData(SerializationInfo 
info,StreamingContext context) 
+        {
+            base.GetObjectData(info, context);
+            
+            // Add custom data, in this case the list of errors when 
serializing.
+            // Thanks Robert Chartier for info: 
http://www.15seconds.com/issue/020903.htm
+            
+            //use the info object to add the items you want serialized
+            info.AddValue("errors", errors, typeof(IList));
+            
+            
+        }
 
         /// <summary>
         /// Provide access to the entire list of errors provided by the 
PostgreSQL backend.
@@ -199,22 +222,28 @@
         /// </summary>
         public override String ToString()
         {
-            StringWriter    S = new StringWriter();
-
-            S.WriteLine("{0}:", this.GetType().FullName);
-
-            foreach (NpgsqlError PgError in Errors)
+        
+            if (Errors != null)
             {
-                AppendString(S, "{0}", PgError.Message);
-                AppendString(S, "Severity: {0}", PgError.Severity);
-                AppendString(S, "Code: {0}", PgError.Code);
-                AppendString(S, "Hint: {0}", PgError.Hint);
+                StringWriter    S = new StringWriter();
+    
+                S.WriteLine("{0}:", this.GetType().FullName);
+    
+                foreach (NpgsqlError PgError in Errors)
+                {
+                    AppendString(S, "{0}", PgError.Message);
+                    AppendString(S, "Severity: {0}", PgError.Severity);
+                    AppendString(S, "Code: {0}", PgError.Code);
+                    AppendString(S, "Hint: {0}", PgError.Hint);
+                }
+    
+                S.Write(StackTrace);
+    
+                return S.ToString();
             }
+            
+            return base.ToString();
 
-            S.Write(StackTrace);
-
-            return S.ToString();
-
         }
 
         /// <summary>

Modified: trunk/mcs/class/Npgsql/Npgsql/NpgsqlParameter.cs
===================================================================
--- trunk/mcs/class/Npgsql/Npgsql/NpgsqlParameter.cs    2005-07-05 22:53:57 UTC 
(rev 46978)
+++ trunk/mcs/class/Npgsql/Npgsql/NpgsqlParameter.cs    2005-07-05 22:55:29 UTC 
(rev 46979)
@@ -60,7 +60,7 @@
         private NpgsqlNativeTypeInfo   type_info;
         private ParameterDirection         direction = 
ParameterDirection.Input;
         private Boolean                                    is_nullable = false;
-        private String                             name;
+        private String                             name = String.Empty;
         private String                             source_column = 
String.Empty;
         private DataRowVersion             source_version = 
DataRowVersion.Current;
         private Object                             value = DBNull.Value;
@@ -161,7 +161,7 @@
             NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, 
CLASSNAME, parameterName, parameterType, size, source_column);
 
             this.ParameterName = parameterName;
-
+            
             type_info = NpgsqlTypesHelper.GetNativeTypeInfo(parameterType);
             if (type_info == null)
                 throw new 
InvalidCastException(String.Format(resman.GetString("Exception_ImpossibleToCast"),
 parameterType));
@@ -420,6 +420,8 @@
             set
             {
                 name = value;
+                if (value == null)
+                    name = String.Empty;
                 if ( (name.Equals(String.Empty)) || ((name[0] != ':') && 
(name[0] != '@')) )
                     name = ':' + name;
 

Modified: trunk/mcs/class/Npgsql/Npgsql/NpgsqlParameterCollection.cs
===================================================================
--- trunk/mcs/class/Npgsql/Npgsql/NpgsqlParameterCollection.cs  2005-07-05 
22:53:57 UTC (rev 46978)
+++ trunk/mcs/class/Npgsql/Npgsql/NpgsqlParameterCollection.cs  2005-07-05 
22:55:29 UTC (rev 46979)
@@ -127,15 +127,15 @@
             NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Add", 
value);
 
             // Do not allow parameters without name.
-            if (value.ParameterName == null) {
-                throw new 
ArgumentNullException(String.Format(this.resman.GetString("Exception_InvalidParameterName"),
 value.ParameterName));
-                                               }
-
-                                               if (value.ParameterName.Trim() 
== String.Empty ||
-               (value.ParameterName.Length == 1 && value.ParameterName[0] == 
':'))
-                throw new 
ArgumentOutOfRangeException(String.Format(this.resman.GetString("Exception_InvalidParameterName"),
 value.ParameterName));
-
+            
             this.InternalList.Add(value);
+            
+            // Check if there is a name. If not, add a name based in the index 
of parameter.
+            if (value.ParameterName.Trim() == String.Empty ||
+            (value.ParameterName.Length == 1 && value.ParameterName[0] == ':'))
+                value.ParameterName = ":" + "Parameter" + (IndexOf(value) + 1);
+        
+            
             return value;
         }
 
@@ -363,7 +363,8 @@
         {
             NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Add", 
value);
             CheckType(value);
-            return this.InternalList.Add(value);
+            this.Add((NpgsqlParameter)value);
+            return IndexOf(value);
         }
 
         bool IList.IsFixedSize {

Modified: trunk/mcs/class/Npgsql/Npgsql/NpgsqlState.resx
===================================================================
--- trunk/mcs/class/Npgsql/Npgsql/NpgsqlState.resx      2005-07-05 22:53:57 UTC 
(rev 46978)
+++ trunk/mcs/class/Npgsql/Npgsql/NpgsqlState.resx      2005-07-05 22:55:29 UTC 
(rev 46979)
@@ -57,7 +57,7 @@
     value   : The object must be serialized into a byte array 
             : using a System.ComponentModel.TypeConverter
             : and then encoded with base64 encoding.
-    -->
+    -->
        <xsd:schema id="root" xmlns="" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"; 
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
                <xsd:element name="root" msdata:IsDataSet="true";>
                        <xsd:complexType>
@@ -129,9 +129,13 @@
        </data>
        <data name="Log_ConnectedTo">
                 <value>Connected to: {0}:{1}.</value>
-        </data>
+    </data>
 
        <data name="Log_QuerySent">
                 <value>Query sent: {0}.</value>
-        </data>
+    </data>
+    <data name="Exception_Ssl_RequestError">
+                <value>Ssl connection requested. No Ssl enabled connection 
from this host is configured.</value>
+    </data>    
+        
 </root>

Modified: trunk/mcs/class/Npgsql/NpgsqlTypes/NpgsqlDbType.cs
===================================================================
--- trunk/mcs/class/Npgsql/NpgsqlTypes/NpgsqlDbType.cs  2005-07-05 22:53:57 UTC 
(rev 46978)
+++ trunk/mcs/class/Npgsql/NpgsqlTypes/NpgsqlDbType.cs  2005-07-05 22:55:29 UTC 
(rev 46979)
@@ -33,6 +33,7 @@
         Box,
         Bytea,
         Circle,
+        Char,
         Date,
         Double,
         Integer,
@@ -48,7 +49,7 @@
         Text,
         Time,
         Timestamp,
-       Varchar
+        Varchar
 
     }
 

Modified: trunk/mcs/class/Npgsql/NpgsqlTypes/NpgsqlTypesHelper.cs
===================================================================
--- trunk/mcs/class/Npgsql/NpgsqlTypes/NpgsqlTypesHelper.cs     2005-07-05 
22:53:57 UTC (rev 46978)
+++ trunk/mcs/class/Npgsql/NpgsqlTypes/NpgsqlTypesHelper.cs     2005-07-05 
22:55:29 UTC (rev 46979)
@@ -159,6 +159,17 @@
                 }
 
                 NativeTypeMapping = new NpgsqlNativeTypeMapping();
+                
+                
+                // Conflicting types should have mapped first the non default 
mappings.
+                // For example, char, varchar and text map to DbType.String. 
As the most 
+                // common is to use text with string, it has to be the last 
mapped, in order
+                // to type mapping has the last entry, in this case, text, as 
the map value
+                // for DbType.String.
+                
+                NativeTypeMapping.AddType("char", NpgsqlDbType.Char, 
DbType.String, true, null);
+                
+                NativeTypeMapping.AddType("varchar", NpgsqlDbType.Varchar, 
DbType.String, true, null);
 
                 NativeTypeMapping.AddType("text", NpgsqlDbType.Text, 
DbType.String, true, null);
 
@@ -167,8 +178,7 @@
                 NativeTypeMapping.AddDbTypeAlias("text", 
DbType.AnsiStringFixedLength);
                 NativeTypeMapping.AddTypeAlias("text", typeof(String));
 
-               NativeTypeMapping.AddType("varchar", NpgsqlDbType.Varchar, 
DbType.String, true, null);
-
+                                                
                 NativeTypeMapping.AddType("bytea", NpgsqlDbType.Bytea, 
DbType.Binary, true,
                 new 
ConvertNativeToBackendHandler(BasicNativeToBackendTypeConverter.ToBinary));
 
@@ -183,9 +193,11 @@
                 null);
 
                 NativeTypeMapping.AddTypeAlias("int2", typeof(Int16));
+                                
+                NativeTypeMapping.AddDbTypeAlias("int2", DbType.Byte);
                 
-                NativeTypeMapping.AddDbTypeAlias("int2", DbType.Byte);
-
+                NativeTypeMapping.AddTypeAlias("int2", typeof(Byte));
+                
                 NativeTypeMapping.AddType("int4", NpgsqlDbType.Integer, 
DbType.Int32, false,
                 null);
 
@@ -196,12 +208,12 @@
 
                 NativeTypeMapping.AddTypeAlias("int8", typeof(Int64));
 
-                NativeTypeMapping.AddType("float4", NpgsqlDbType.Real, 
DbType.Single, false,
+                NativeTypeMapping.AddType("float4", NpgsqlDbType.Real, 
DbType.Single, true,
                 null);
 
                 NativeTypeMapping.AddTypeAlias("float4", typeof(Single));
 
-                NativeTypeMapping.AddType("float8", NpgsqlDbType.Double, 
DbType.Double, false,
+                NativeTypeMapping.AddType("float8", NpgsqlDbType.Double, 
DbType.Double, true,
                 null);
 
                 NativeTypeMapping.AddTypeAlias("float8", typeof(Double));
@@ -290,7 +302,7 @@
                     new NpgsqlBackendTypeInfo(0, "unknown", NpgsqlDbType.Text, 
DbType.String, typeof(String),
                         null),
 
-                    new NpgsqlBackendTypeInfo(0, "char", NpgsqlDbType.Text, 
DbType.String, typeof(String),
+                    new NpgsqlBackendTypeInfo(0, "char", NpgsqlDbType.Char, 
DbType.String, typeof(String),
                         null),
 
                     new NpgsqlBackendTypeInfo(0, "bpchar", NpgsqlDbType.Text, 
DbType.String, typeof(String),
@@ -534,6 +546,7 @@
         private NpgsqlDbType     _NpgsqlDbType;
         private DbType           _DbType;
         private Boolean          _Quote;
+        private Boolean          _UseSize;
         
         static NpgsqlNativeTypeInfo()
         {
@@ -557,6 +570,16 @@
             _DbType = DbType;
             _Quote = Quote;
             _ConvertNativeToBackend = ConvertNativeToBackend;
+            
+            
+            // The only parameters types which use length currently supported 
are char and varchar. Check for them.
+            
+            if ( (NpgsqlDbType == NpgsqlDbType.Char)
+                || (NpgsqlDbType == NpgsqlDbType.Varchar))
+                
+                _UseSize = true;
+            else
+                _UseSize = false;
         }
 
         /// <summary>
@@ -585,6 +608,13 @@
         { get { return _Quote; } }
 
         /// <summary>
+        /// Use parameter size information.
+        /// </summary>
+        public Boolean UseSize
+        { get { return _UseSize; } }
+        
+        
+        /// <summary>
         /// Perform a data conversion from a native object to
         /// a backend representation.
         /// DBNull and null values are handled differently depending if a 
plain query is used
@@ -608,7 +638,7 @@
                 return "NULL";  // Plain queries exptects null values as 
string NULL. 
             
             if (_ConvertNativeToBackend != null)
-                return QuoteString(_ConvertNativeToBackend(this, NativeData));
+                return (this.Quote ? QuoteString(_ConvertNativeToBackend(this, 
NativeData)) : _ConvertNativeToBackend(this, NativeData));
             else
             {
                 
@@ -621,12 +651,14 @@
                 }
                 else if (NativeData is IFormattable)
                 {
-                    return QuoteString(((IFormattable) 
NativeData).ToString(null, ni).Replace("'", "''").Replace("\\", "\\\\"));
+                    return (this.Quote ? QuoteString(((IFormattable) 
NativeData).ToString(null, ni).Replace("'", "''").Replace("\\", "\\\\")) : 
+                    ((IFormattable) NativeData).ToString(null, 
ni).Replace("'", "''").Replace("\\", "\\\\"));
                     
                 }
                 
                 // Do special handling of strings when in simple query. Escape 
quotes and backslashes.
-                return QuoteString(NativeData.ToString().Replace("'", 
"''").Replace("\\", "\\\\").Replace("\0", "\\0"));
+                return (this.Quote ? 
QuoteString(NativeData.ToString().Replace("'", "''").Replace("\\", 
"\\\\").Replace("\0", "\\0")) : 
+                NativeData.ToString().Replace("'", "''").Replace("\\", 
"\\\\").Replace("\0", "\\0"));
                 
             }
     

_______________________________________________
Mono-patches maillist  -  [email protected]
http://lists.ximian.com/mailman/listinfo/mono-patches

Reply via email to