Golang - pgbouncer and transaction usage

Technical information

  • go version 1.2
  • postrgres library for go bmizerany / pq

This problem is driving me crazy, and I hope someone can help.

I developed a golang application to read data from a postgres database, and for each record, make an http request and then update the database.

It is quite simple. However, we have a pgbouncer. The configuration we have for pgbouncer is that it does not support prepared statements. Step-by-step completion of all requests in the prepared message. The way around this for pgbouncer is to create a transaction. This is good and good for things like insert / update / delete.

In the case of the select statement, I transfer it to the transaction:

func TransactionQuery(db *sql.DB, baseQuery string) (rows *sql.Rows, code int, err error) {
        tx, txErr := db.Begin()
        if txErr != nil {
            return nil, -1, txErr
        }

        selectStmt, prepErr := tx.Prepare(baseQuery)
        if prepErr != nil {
            return nil, -1, fmt.Errorf("Failed to prepare statment: %s Error: %v", baseQuery, prepErr)
        }

        defer func() {
            if stmtErr := selectStmt.Close(); stmtErr != nil {
                rows = nil
                code = -2
                err = fmt.Errorf("Failed to close statement: %v.", stmtErr)
            }
        }()

        rows, err = selectStmt.Query()
        if err != nil {
            fmt.Errorf("Failed to retrieve data: %v", err)
            return nil, -1, err
        }
        return rows, 0, nil
    }

(hhmm, , ) AsS , . pg , " ".

tx.Commit() tx.Rollback(), :

"unknown response for simple query '3'"

"unknown response for simple query 'D'"

, Go? , pgbouncer.ini, lib/pq , , .

, tx Go ?

:

func TransactionQuery(db *sql.DB, baseQuery string) (rows *sql.Rows, code int, err error) {
    tx, txErr := db.Begin()
    if txErr != nil {
        return nil, -1, txErr
    }

    /*selectStmt, prepErr := tx.Prepare(baseQuery)
      if prepErr != nil {
          return nil, -1, fmt.Errorf("Failed to prepare statment: %s Error: %v", baseQuery, prepErr)
      }
    */
    rows, err = tx.Query(baseQuery)
    if err != nil {
        fmt.Errorf("Failed to retrieve data: %v", err)
        return nil, -1, err
    }

    /*    if stmtErr := selectStmt.Close(); stmtErr != nil {
          rows = nil
          code = -2
          err = fmt.Errorf("Failed to close statement: %v.", stmtErr)
      }*/

    if txCloseErr := tx.Commit(); txErr != nil {
        rows = rows
        code = -3
        err = txCloseErr
    }
    return rows, 0, nil
}

:

pq: unexpected describe rows response: '3'

, select . , . . .

+4
2

, , .

, , ( ) . , -, . , , .

, . , , . .

+2

Tx.Query sql.Rows, . , . .

.

0

Source: https://habr.com/ru/post/1536083/


All Articles