github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/db/log_conn.go (about)

     1  package db
     2  
     3  import (
     4  	"context"
     5  	"database/sql"
     6  	"strings"
     7  
     8  	"code.cloudfoundry.org/lager"
     9  	"github.com/Masterminds/squirrel"
    10  )
    11  
    12  // Log returns a wrapper of DB connection which contains a wraper of DB transactions
    13  // so all queries could be logged by givin logger
    14  func Log(logger lager.Logger, conn Conn) Conn {
    15  	return &logConn{
    16  		Conn:   conn,
    17  		logger: logger,
    18  	}
    19  }
    20  
    21  type logConn struct {
    22  	Conn
    23  
    24  	logger lager.Logger
    25  }
    26  
    27  func (c *logConn) Begin() (Tx, error) {
    28  	tx, err := c.Conn.Begin()
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  
    33  	return &logDbTx{Tx: tx, logger: c.logger}, nil
    34  }
    35  
    36  func (c *logConn) Query(query string, args ...interface{}) (*sql.Rows, error) {
    37  	c.logger.Debug("query", lager.Data{"query": strip(query)})
    38  	return c.Conn.Query(query, args...)
    39  }
    40  
    41  func (c *logConn) QueryRow(query string, args ...interface{}) squirrel.RowScanner {
    42  	c.logger.Debug("query-row", lager.Data{"query": strip(query)})
    43  	return c.Conn.QueryRow(query, args...)
    44  }
    45  
    46  func (c *logConn) Exec(query string, args ...interface{}) (sql.Result, error) {
    47  	c.logger.Debug("exec", lager.Data{"query": strip(query)})
    48  	return c.Conn.Exec(query, args...)
    49  }
    50  
    51  func strip(query string) string {
    52  	return strings.Join(strings.Fields(query), " ")
    53  }
    54  
    55  type logDbTx struct {
    56  	Tx
    57  
    58  	logger lager.Logger
    59  }
    60  
    61  func (t *logDbTx) Query(query string, args ...interface{}) (*sql.Rows, error) {
    62  	t.logger.Debug("tx-query", lager.Data{"query": strip(query)})
    63  	return t.Tx.Query(query, args...)
    64  }
    65  
    66  func (t *logDbTx) QueryRow(query string, args ...interface{}) squirrel.RowScanner {
    67  	t.logger.Debug("tx-query-row", lager.Data{"query": strip(query)})
    68  	return t.Tx.QueryRow(query, args...)
    69  }
    70  
    71  func (t *logDbTx) Exec(query string, args ...interface{}) (sql.Result, error) {
    72  	t.logger.Debug("tx-exec", lager.Data{"query": strip(query)})
    73  	return t.Tx.Exec(query, args...)
    74  }
    75  
    76  func (t *logDbTx) QueryRowContext(ctx context.Context, query string, args ...interface{}) squirrel.RowScanner {
    77  	t.logger.Debug("tx-query-row-context", lager.Data{"query": strip(query)})
    78  	return t.Tx.QueryRowContext(ctx, query, args...)
    79  }