/*
 * call-seq:
 *    PGconn.connect_start(connection_hash)       -> PGconn
 *    PGconn.connect_start(connection_string)     -> PGconn
 *    PGconn.connect_start(host, port, options, tty, dbname, login, password) ->  PGconn
 *
 * This is an asynchronous version of PGconn.connect().
 *
 * Use PGconn#connect_poll to poll the status of the connection.
 *
 * NOTE: this does *not* set the connection's +client_encoding+ for you if 
 * Encoding.default_internal is set. To set it after the connection is established, 
 * call PGconn#internal_encoding=. You can also set it automatically by setting 
 * ENV['PGCLIENTENCODING'], or include the 'options' connection parameter.
 * 
 */
static VALUE
pgconn_s_connect_start(int argc, VALUE *argv, VALUE self)
{
    PGconn *conn = NULL;
    VALUE rb_conn;
    VALUE conninfo;
    VALUE error;

    /*
     * PGconn.connect_start must act as both alloc() and initialize()
     * because it is not invoked by calling new().
     */
    rb_conn = pgconn_alloc(rb_cPGconn);

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

    if(conn == NULL)
        rb_raise(rb_ePGError, "PQconnectStart() unable to allocate structure");
    if (PQstatus(conn) == CONNECTION_BAD) {
        error = rb_exc_new2(rb_ePGError, PQerrorMessage(conn));
        rb_iv_set(error, "@connection", self);
        rb_exc_raise(error);
    }

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

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