Skip to content

Add asynchronous notification feature into db_postgres lib #25

Open
@geohuz

Description

@geohuz

Summary

As stated in Postgresql official documentation: https://www.postgresql.org/docs/current/libpq-notify.html , it is missed from db_connector/postgres.

Description

As the implementaion of the code require asyncdispatch lib, I'm not sure if it is a proper way to put into the db_connector.

Alternatives

As the implement requires less than dozen line of codes, put them into any third party package seems awkward.

Examples

Here is the simple implementation of the pg's async notfication with asyncdispatch:

import asyncdispatch
import db_connector/db_postgres
import db_connector/postgres

type PGNotify = tuple [channel: string, message: string]

let conn = db_postgres.open("localhost:xxx", "postgres", "", "")
# listen to notification
conn.exec(sql(""" LISTEN "testChannel" """))

proc recvNotify(conn: DbConn): Future[PGNotify] =
  let fd = AsyncFD(pqsocket(conn))
  let retFuture = newFuture[PGNotify]()

  proc cb(fd: AsyncFD): bool {.closure, gcsafe.} =
    if not retFuture.finished:
      if pqconsumeInput(conn)==0:
        retFuture.fail(newException(ValueError, $pqerrorMessage(conn)))
      else:
        let notify = pqnotifies(conn)
        if notify != nil:
          unregister(fd) 
          retFuture.complete((channel: $notify.relname, message: $notify.extra))

    return true

  register(fd)  
  addRead(fd, cb) 
  return retFuture

proc processPgNotify() {.async.} =
  while true:
    let notify = await recvNotify(conn)
    echo "channel, message ", notify.channel, notify.message

asyncCheck processPgNotify()
runForever()

Backwards Compatibility

No response

Links

https://www.postgresql.org/docs/current/libpq-notify.html

example of official documentation(in C): https://www.postgresql.org/docs/current/libpq-example.html#LIBPQ-EXAMPLE-2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions