/*
 * Document-method: new
 *
 * call-seq:
 *    PGconn.new(connection_hash) -> PGconn
 *    PGconn.new(connection_string) -> PGconn
 *    PGconn.new(host, port, options, tty, dbname, login, password) ->  PGconn
 * 
 * Create a connection to the specified server.
 * 
 * [+host+]
 *   server hostname
 * [+hostaddr+]
 *   server address (avoids hostname lookup, overrides +host+)
 * [+port+]
 *   server port number
 * [+dbname+]
 *   connecting database name
 * [+user+]
 *   login user name
 * [+password+]
 *   login password
 * [+connect_timeout+]
 *   maximum time to wait for connection to succeed
 * [+options+]
 *   backend options
 * [+tty+]
 *   (ignored in newer versions of PostgreSQL)
 * [+sslmode+]
 *   (disable|allow|prefer|require)
 * [+krbsrvname+]
 *   kerberos service name
 * [+gsslib+]
 *   GSS library to use for GSSAPI authentication
 * [+service+]
 *   service name to use for additional parameters
 * 
 * Examples:
 * 
 *   # As a Hash
 *   PGconn.connect( :dbname => 'test', :port => 5432 )
 *   
 *   # As a String
 *   PGconn.connect( "dbname=test port=5432" )
 *   
 *   # As an Array
 *   PGconn.connect( nil, 5432, nil, nil, 'test', nil, nil )
 *  
 * On failure, it raises a PGError.
 */
static VALUE
pgconn_init(int argc, VALUE *argv, VALUE self)
{
    PGconn *conn = NULL;
    VALUE conninfo;
    VALUE error;

    conninfo = parse_connect_args(argc, argv, self);
    conn = PQconnectdb(StringValuePtr(conninfo));

    if(conn == NULL)
        rb_raise(rb_ePGError, "PQconnectStart() unable to allocate structure");

    Check_Type(self, T_DATA);
    DATA_PTR(self) = conn;

    if (PQstatus(conn) == CONNECTION_BAD) {
        error = rb_exc_new2(rb_ePGError, PQerrorMessage(conn));
        rb_iv_set(error, "@connection", self);
        rb_exc_raise(error);
    }

    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, self, pgconn_finish, self);
    }
    return self;
}