On this page:
6.1 Connection utilities

6 Utilities

6.1 Connection utilities

(connection-generator generator    
  [#:timeout timeout])  connection?
  generator : (-> connection?)
  timeout : (or/c #f (and/c rational? positive?)) = #f
Creates a virtual connection that creates actual connections on demand using the generator function. A connection generator encapsulates a mapping of threads to actual connections. When a query function is called with a connection generator, the current thread’s associated actual connection is used to execute the query. If there is no actual connection associated with the current thread, one is obtained by calling generator. An actual connection is disconnected when its associated thread dies or if timeout seconds elapse since the actual connection was last used.

When given a connection produced by connection-generator, connected? indicates whether there is an actual connection associated with the current thread. Likewise, disconnect causes the current actual connection associated with the thread (if there is one) to be disconnected, but the connection will be recreated if a query function is executed.


  > (define c
       (lambda ()
         (printf "connecting!\n")
         (postgresql-connect ....))))
  > (connected? c)


  > (query-value c "select 1")



  > (connected? c)


  > (void (thread (lambda () (displayln (query-value c "select 2")))))



  > (disconnect c)
  > (connected? c)


  > (query-value c "select 3")



Connections produced by connection-generator may not be used with the prepare function. However, they may still be used to execute parameterized queries expressed as strings or encapsulated via statement-generator.


  > (prepare c "select 2 + $1")

  prepare: cannot prepare statement with connection-generator

  > (query-value c "select 2 + $1" 2)


  > (define pst (statement-generator "select 2 + $1"))
  > (query-value c pst 3)


Creates a proxy for connection c. All queries performed through the proxy are kill-safe; that is, if a thread is killed during a call to a query function such as query, the connection will not become locked or damaged. (Connections are normally thread-safe but not kill-safe.)

Note: A kill-safe connection whose underlying connection uses ports to communicate with a database server is not protected from a custodian shutting down its ports.