brianc / node-pg-cursor

Query cursor extension for node-postgres
78 stars 30 forks source link

Event handler leak on noData queries #31

Open andvgal opened 7 years ago

andvgal commented 7 years ago

Obviously it's not the purpose of pg-cursor, but sometimes you do not know type of query in advance, but need to implement a common query execution logic.

If noData (INSERT/UPDATE/DELETE without RETURNING clause) queries are run through cursor then dangling rowDescription events are left on connection. It leads to Node,js memory leak warning.

Simple solution is to clear rowDescription on noData event, like:

  const ifNoData = () => {
    this.state = 'idle'
    this._shiftQueue()
    con.removeListener('rowDescription', onRowData)
  }

  const onRowData = () => {
    con.removeListener('noData', ifNoData)
  }

  if (this._conf.types) {
    this._result._getTypeParser = this._conf.types.getTypeParser
  }

  con.once('noData', ifNoData)
  con.once('rowDescription', onRowData)

However, it seems the code is not completely safe. We need to ensure that all introduced event handlers are removed upon cursor close by (error, noData, done, forced close, etc.)