vapor / postgres-nio

🐘 Non-blocking, event-driven Swift client for PostgreSQL.
https://api.vapor.codes/postgresnio/documentation/postgresnio/
MIT License
304 stars 70 forks source link

Get count of active connection #469

Closed gulivero1773 closed 2 months ago

gulivero1773 commented 2 months ago

Need add method for get active connection of database. I do library for health check and I need to get count active connection from psql. I send sql request - SELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active'; and I have this struct in response - PostgresRandomAccessRow, but I don't have permission for get lookupTable and get count of active connections

MahdiBM commented 2 months ago

I'm pretty sure the current API is sufficient, but not 100% sure of the function names.

I think you shouldn't even use PostgresRandomAccessRow row when possible. Just use PostgresRow and decode the rows into a tuple:

let (field1, field2) = myPostresRow.decode((String, Int).self, context: .default)

Make sure the tuple covers all rows that are returned, and in order. I'd suggest not using * and specifying the fields.

You could still use PostgresRandomAccessRow and its subscripts, but using PostgresRow like i mentioned is the best / most-performant way.

MahdiBM commented 2 months ago

Feel free to let me know if i'm wrong or you'll need some more functions marked as API (and for what reasons).

gulivero1773 commented 2 months ago
Знімок екрана 2024-04-24 о 15 20 51

@MahdiBM When I use this code I have fatal error

gulivero1773 commented 2 months ago
let rows = try await (app.db(.psql) as? PostgresDatabase)?.simpleQuery("SELECT * FROM pg_stat_activity WHERE datname = 'test' and state = 'active';").get()
let row = rows?.first?.makeRandomAccess()
rows?.forEach { rowNew in
    let res = try? rowNew.decode((String, Int).self, context: .default)
}
MahdiBM commented 2 months ago

@gulivero1773 https://github.com/vapor/postgres-nio/issues/469#issuecomment-2074485111

Make sure the tuple covers all rows that are returned, and in order. I'd suggest not using * and specifying the fields.

Please mention the fatal error if you still get it.

MahdiBM commented 2 months ago

The tuple i put there was purely a showcase. You'd need to change it to something that works for you. Each element in the tuple represents a column of each row of the response you're getting back. Also make sure the element types are correct.