lastval (PGconn)

    /*
     * call-seq:
     *   conn.lastval -> Integer
     *
     * Returns the sequence value returned by the last call to the PostgreSQL function <tt>nextval(sequence_name)</tt>. Equivalent to <tt>conn.query('select lastval()').first.first</tt>.
     *
     * This functionality is only available with PostgreSQL 8.1 and newer.
     * See the PostgreSQL documentation on lastval[http://www.postgresql.org/docs/current/interactive/functions-sequence.html] for more information.
     */
    static VALUE
    pgconn_lastval(obj)
        VALUE obj;
    {
        PGconn *conn = get_pgconn(obj);
        PGresult *result;
        VALUE lastval, error;

        result = PQexec(conn, "select lastval()");
        if (!result) rb_raise(rb_ePGError, PQerrorMessage(conn));

        switch (PQresultStatus(result)) {
        case PGRES_TUPLES_OK:
          lastval = rb_cstr2inum(PQgetvalue(result, 0, 0), 10);
          PQclear(result);
          return lastval;

        case PGRES_BAD_RESPONSE:
        case PGRES_FATAL_ERROR:
        case PGRES_NONFATAL_ERROR:
          error = rb_str_new2(PQresultErrorMessage(result));
          PQclear(result);
          rb_raise(rb_ePGError, StringValuePtr(error));

        default:
          PQclear(result);
          rb_raise(rb_ePGError, "unknown lastval");
        }
    }