Index: connection.cpp
===================================================================
--- connection.cpp	(revision 7514)
+++ connection.cpp	(working copy)
@@ -11,10 +11,173 @@
 
 #include "pgAgent.h"
 
+#include <wx/regex.h>
+#include <wx/tokenzr.h>
+
 DBconn *DBconn::primaryConn;
 wxString DBconn::basicConnectString;
 static wxMutex s_PoolLock;
 
+bool connInfo::IsValidIP()
+{
+    if (host.IsEmpty())
+        return false;
+
+    // check for IPv4 format
+    wxStringTokenizer tkip4(host, wxT("."));
+    int count = 0;
+    
+    while (tkip4.HasMoreTokens())
+    {
+        unsigned long val = 0;
+        if (!tkip4.GetNextToken().ToULong(&val))
+            break;
+        if (count == 0 || count == 3)
+            if (val > 0 && val < 255)
+                count++;
+            else
+                break;
+        else if (val >= 0 && val < 255)
+            count++;
+        else
+            break;
+    }
+
+    if (count == 4)
+        return true;
+
+    // check for IPv6 format
+    wxStringTokenizer tkip6(host, wxT(":"));
+    count = 0;
+    
+    while (tkip6.HasMoreTokens())
+    {
+        unsigned long val = 0;
+        wxString strVal = tkip6.GetNextToken();
+        if (strVal.Length() > 4 || !strVal.ToULong(&val, 16))
+            return false;
+        count++;
+    }
+    if (count <= 8)
+        return true;
+    
+    // TODO:: We're not supporting mix mode (x:x:x:x:x:x:d.d.d.d)
+    //        i.e. ::ffff:12.34.56.78
+    return false;
+}
+
+wxString connInfo::getConnectionString()
+{
+    wxString connStr;
+    
+    // Check if it has valid connection info
+    if (!isValid)
+        return connStr;
+
+    // User
+    connStr = wxT("user=") + user;
+
+    // Port
+    if (port != 0)
+    {
+        wxString portStr;
+        portStr.Printf(wxT("%ld"), port);
+        connStr += wxT(" port=") + portStr;
+    }
+
+    // host or hostaddr
+    if (!host.IsEmpty())
+        if (IsValidIP())
+           connStr += wxT(" hostaddr=") + host;
+        else
+           connStr += wxT(" host=") + host;
+
+    // connection timeout
+    if (connection_timeout != 0)
+    {
+        wxString val;
+        val.Printf(wxT("%ld"), connection_timeout);
+        connStr += wxT(" connection_timeout=") + val;
+    }
+
+    // password
+    if (!password.IsEmpty())
+       connStr += wxT(" password=") + password;
+
+	if (!dbname.IsEmpty())
+		connStr += wxT(" dbname=") + dbname;
+
+    LogMessage(wxString::Format(_("Connection Information:")), LOG_DEBUG);
+    LogMessage(wxString::Format(_("     user         : %s"), user.c_str()), LOG_DEBUG);
+    LogMessage(wxString::Format(_("     port         : %ld"), port), LOG_DEBUG);
+    LogMessage(wxString::Format(_("     host         : %s"), host.c_str()), LOG_DEBUG);
+    LogMessage(wxString::Format(_("     dbname       : %s"), dbname.c_str()), LOG_DEBUG);
+    LogMessage(wxString::Format(_("     password     : %s"), password.c_str()), LOG_DEBUG);
+    LogMessage(wxString::Format(_("     conn timeout : %ld"), connection_timeout), LOG_DEBUG);
+
+    return connStr;
+}
+
+
+connInfo connInfo::getConnectionInfo(wxString connStr)
+{
+    connInfo cnInfo;
+
+    wxRegEx propertyExp;
+    bool res = propertyExp.Compile(wxT("(([ ]*[\t]*)+)="));
+
+    propertyExp.ReplaceAll(&connStr, wxT("="));
+
+    res = propertyExp.Compile(wxT("=(([ ]*[\t]*)+)"));
+    propertyExp.ReplaceAll(&connStr, wxT("="));
+
+    wxArrayString tokens = wxStringTokenize(connStr, wxT("\t \n\r"));
+    
+    unsigned int index = 0;
+    while (index < tokens.Count())
+    {
+        wxString prop, value;
+
+        wxArrayString pairs = wxStringTokenize(tokens[index++], wxT("="));
+
+        if (pairs.GetCount()!= 2)
+            return cnInfo;
+
+        prop=pairs[0];
+        value=pairs[1];
+
+        if (prop.CmpNoCase(wxT("user")) == 0)
+            cnInfo.user = value;
+        else if (prop.CmpNoCase(wxT("host")) == 0 || prop.CmpNoCase(wxT("hostAddr")) == 0)
+            cnInfo.host = value;
+        else if (prop.CmpNoCase(wxT("port")) == 0)
+        {
+            if (!value.ToULong(&cnInfo.port))
+                // port must be an unsigned integer
+                return cnInfo;
+        }
+        else if (prop.CmpNoCase(wxT("password")) == 0)
+            cnInfo.password = value;
+        else if (prop.CmpNoCase(wxT("connection_timeout")) == 0)
+        {
+            if (!value.ToULong(&cnInfo.connection_timeout))
+                // connection timeout must be an unsigned interger
+                return cnInfo;
+        }
+        else if (prop.CmpNoCase(wxT("dbname")) == 0)
+            cnInfo.dbname = value;
+        else
+            // Not valid property found
+            return cnInfo;
+    }
+
+    if (cnInfo.user.IsEmpty())
+        cnInfo.isValid = false;
+    else
+        cnInfo.isValid = true;
+    return cnInfo;
+}
+
 DBconn::DBconn(const wxString &db)
 {
     dbname = db;
@@ -23,19 +186,52 @@
     prev=0;
     majorVersion=0;
     minorVersion=0;
+    // This is a local database call
     Connect(basicConnectString  + wxT(" dbname=") + dbname);
 }
 
 
 DBconn::DBconn(const wxString &connectString, const wxString &db)
 {
-    dbname = db;
     inUse = false;
     next=0;
     prev=0;
     majorVersion=0;
     minorVersion=0;
-    Connect(connectString);
+
+    if (connectString.IsEmpty())
+    {
+        // This is a sql call to a local database. 
+        // No connection string found. Use basicConnectString.
+        dbname = db;
+        Connect(basicConnectString  + wxT(" dbname=") + dbname);
+    }
+    else
+    {
+        // SQL call using connection string
+        connInfo cnInfo = connInfo::getConnectionInfo(connectString);
+        if (!cnInfo.isValid)
+        {
+            conn = NULL;
+            lastError = wxT("Connection Error: not a valid connection string : ") + connectString;
+        }
+        else
+        {
+            // connection string does not contain database information
+            // Append database information
+            if (db.IsEmpty())
+                dbname=wxT("postgres");
+            else
+                dbname=db;
+            if (cnInfo.dbname.IsEmpty())
+            {
+                // database not found in the connection string
+                // Use provided database
+                cnInfo.dbname = dbname;
+            }
+            Connect(cnInfo.getConnectionString());
+        }
+    }
 }
 
 
@@ -44,11 +240,8 @@
     LogMessage(wxString::Format(_("Creating DB connection: %s"), connectString.c_str()), LOG_DEBUG);
     wxCharBuffer cstrUTF=connectString.mb_str(wxConvUTF8);
     conn=PQconnectdb(cstrUTF);
-    if (PQstatus(conn) == CONNECTION_OK)
+    if (PQstatus(conn) != CONNECTION_OK)
     {
-    }
-    else
-    {
         lastError = wxString::FromAscii(PQerrorMessage(conn));
         PQfinish(conn);
         conn=0;
@@ -131,11 +324,11 @@
 }
 
 
-DBconn *DBconn::Get(const wxString &db)
+DBconn *DBconn::Get(const wxString &connStr, const wxString &db)
 {
-    if (db.IsEmpty())
+	if (db.IsEmpty() && connStr.IsEmpty())
     {
-        LogMessage(_("Cannot allocate connection - no database specified!"), LOG_WARNING);
+        LogMessage(_("Cannot allocate connection - no database or connection string specified!"), LOG_WARNING);
         return NULL;
     }
 
@@ -146,7 +339,7 @@
     // find an existing connection
     do
     {
-        if (db == thisConn->dbname && !thisConn->inUse)
+        if (db == thisConn->dbname && (connStr == thisConn->connStr || (connStr.IsEmpty() && thisConn->connStr == basicConnectString)) && !thisConn->inUse)
         {
             LogMessage(wxString::Format(_("Allocating existing connection to database %s"), thisConn->dbname.c_str()), LOG_DEBUG);
             thisConn->inUse = true;
@@ -161,7 +354,7 @@
 
 
     // No suitable connection was found, so create a new one.
-    DBconn *newConn=new DBconn(db);
+    DBconn *newConn=new DBconn(connStr, db);
     if (newConn->conn)
     {
         LogMessage(wxString::Format(_("Allocating new connection to database %s"), newConn->dbname.c_str()), LOG_DEBUG);
@@ -172,6 +365,7 @@
     else
     {
         LogMessage(wxString::Format(_("Failed to create new connection to database %s"), db.c_str()), LOG_WARNING);
+        LogMessage(wxString::Format(_("  Error message from connection : (%s)"), newConn->GetLastError().c_str()), LOG_WARNING);
         return NULL;
     }
 
Index: pgagent.sql
===================================================================
--- pgagent.sql	(revision 7514)
+++ pgagent.sql	(working copy)
@@ -67,7 +67,8 @@
 jstenabled           bool                 NOT NULL DEFAULT true,
 jstkind              char                 NOT NULL CHECK (jstkind IN ('b', 's')), -- batch, sql
 jstcode              text                 NOT NULL,
-jstdbname            name                 NOT NULL DEFAULT '' CHECK ((jstdbname != '' AND jstkind = 's') OR (jstdbname = '' AND jstkind = 'b')),
+jstconnstr           text                 NOT NULL DEFAULT '' CHECK ((jstconnstr != '' AND jstkind = 's' ) OR (jstconnstr = '' AND (jstkind = 'b' OR jstdbname != ''))),
+jstdbname            name                 NOT NULL DEFAULT '' CHECK ((jstdbname != '' AND jstkind = 's' ) OR (jstdbname = '' AND (jstkind = 'b' OR jstconnstr != ''))),
 jstonerror           char                 NOT NULL CHECK (jstonerror IN ('f', 's', 'i')) DEFAULT 'f', -- fail, success, ignore
 jscnextrun           timestamptz          NULL
 ) WITHOUT OIDS;
Index: include/connection.h
===================================================================
--- include/connection.h	(revision 7514)
+++ include/connection.h	(working copy)
@@ -18,6 +18,26 @@
 class DBresult;
 
 
+struct connInfo
+{
+public:
+    connInfo() { isValid = false; connection_timeout = 0; port = 0; }
+    wxString      user;
+    unsigned long port;
+    wxString      host;
+    wxString      dbname;
+    unsigned long connection_timeout;
+    wxString      password;
+    bool          isValid;
+
+    wxString getConnectionString();
+    static connInfo getConnectionInfo(wxString connStr);
+
+protected:
+    bool IsValidIP();
+};
+
+
 class DBconn
 {
 protected:
@@ -30,11 +50,12 @@
 
     bool BackendMinimumVersion(int major, int minor);
 
-    static DBconn *Get(const wxString &db);
+    static DBconn *Get(const wxString &connStr, const wxString &db);
     static DBconn *InitConnection(const wxString &connectString);
 
     static void ClearConnections(bool allIncludingPrimary=false);
     static void SetBasicConnectString(const wxString &bcs) { basicConnectString = bcs; }
+    static const wxString& GetBasicConnectString() { return basicConnectString; }
 
     wxString GetLastError();
     wxString GetDBname() { return dbname; }
@@ -55,6 +76,7 @@
 	static DBconn *primaryConn;
 
     wxString dbname, lastError;
+    wxString connStr;
     PGconn *conn;
 	DBconn *next, *prev;
     bool inUse;
Index: pgagent_update.sql
===================================================================
--- pgagent_update.sql	(revision 0)
+++ pgagent_update.sql	(revision 0)
@@ -0,0 +1,4 @@
+ALTER TABLE pgagent.pga_jobstep ADD COLUMN jstconnstr text NOT NULL DEFAULT '' CONSTRAINT pga_jobstep_connstr_check CHECK ((jstconnstr != '' AND jstkind = 's' ) OR (jstconnstr = '' AND (jstkind = 'b' OR jstdbname != '')));
+ALTER TABLE pgagent.pga_jobstep DROP CONSTRAINT pga_jobstep_check;
+
+ALTER TABLE pgagent.pga_jobstep ADD CONSTRAINT pga_jobstep_dbname_check CHECK ((jstdbname != '' AND jstkind = 's' ) OR (jstdbname = '' AND (jstkind = 'b' OR jstconnstr != '')));
Index: job.cpp
===================================================================
--- job.cpp	(revision 7514)
+++ job.cpp	(working copy)
@@ -78,7 +78,7 @@
 {
     int rc=0;
     DBresult *steps=threadConn->Execute(
-        wxT("SELECT jstid, jstkind, jstdbname, jstcode, jstonerror ")
+        wxT("SELECT * ")
         wxT("  FROM pgagent.pga_jobstep ")
         wxT(" WHERE jstenabled ")
         wxT("   AND jstjobid=") + jobid +
@@ -127,7 +127,10 @@
         {
             case 's':
             {
-                stepConn=DBconn::Get(steps->GetString(wxT("jstdbname")));
+                wxString jstdbname = steps->GetString(wxT("jstdbname"));
+                wxString jstconnstr = steps->GetString(wxT("jstconnstr"));
+                
+                stepConn=DBconn::Get(jstconnstr, jstdbname);
                 if (stepConn)
                 {
                     LogMessage(wxString::Format(_("Executing SQL step %s (part of job %s)"), stepid.c_str(), jobid.c_str()), LOG_DEBUG);
@@ -344,7 +347,7 @@
     runnable = false;
     jobid = jid;
 
-    DBconn *threadConn=DBconn::Get(serviceDBname);
+    DBconn *threadConn=DBconn::Get(DBconn::GetBasicConnectString(), serviceDBname);
     job = new Job(threadConn, jobid);
 
     if (job->Runnable())
