       @sqls.push data
 
     @inPorts.in.on "disconnect", =>
+      client = clients[@url]
       token = @token
       query = _.flatten(@sqls).join(";\n")
 
-      unless client[@url]?
+      unless client?
         throw new Error "Server connection has not yet been established"
       unless token?
         throw new Error "Missing token for return connection"
       unless query?
         throw new Error "Missing query to execute"
 
-      result = client[@url].query query
+      result = client.query query
 
       # Send row forward
       result.on "row", (row, result) =>

noflo = require("noflo")

# Pool all queries through a single connection for each database
client = {}

class Client extends noflo.Component



  startServer: (url) ->
    @endServer url
    clients[url] = new pg.Client url
    clients[url].connect()

  endServer: (url) ->
    if url?
      clients[url]?.end()
    else
      clients[url].end() for url in _.keys clients

exports.getComponent = -> new Client
