arcapos / luapgsql

Lua binding for PostgreSQL
108 stars 24 forks source link

Add way to check if connection object has been finished #30

Closed daurnimator closed 8 years ago

daurnimator commented 8 years ago

Sometimes you would like to know if a connection object is valid before you attempt an operation on it.

Something like lua's io.type where it returns "pgsql connection" if open or "closed pgsql connection" when closed.

Related to https://github.com/daurnimator/cqueues-pgsql/issues/1

mbalmer commented 8 years ago

You can pcall conn:status(). If the connection is finished, it will create an error. In fact all functions that internally go through pgsql_conn() with create an error when the connection object is finished.

daurnimator commented 8 years ago

pcall conn:status()

I was trying to avoid a pcall, but I guess I don't have to.

Though using pcall it's hard to distinguish errors due to connection being closed vs e.g. incorrect arguments.

mbalmer commented 8 years ago

We could change this function to not go through pgsql_conn(), so it does not raise an error on closed connections, but return pgsql.CONNECTION_BAD:

static int
conn_status(lua_State *L)
{
    PGconn **conn;

    conn = luaL_checkudata(L, 1, CONN_METATABLE);
    lua_pushinteger(L, PQstatus(*conn));
    return 1;
}

This would probably make sense.

mbalmer commented 8 years ago

I committed a version that does not raise an error when the connection is finished, but returns pgsql.CONENCTION_BAD (as does the underlying libpq function).