Prepared statement not returning results from pgxpool

Viewed 253

I have the following code:

func (s *SqlServerDatabase) ConnectPool() {
    config, err := pgxpool.ParseConfig(s.Url)
    if err != nil {
        fmt.Println("config Database Fail")
        fmt.Print(err)
    }
    config.AfterRelease = func(conn *pgx.Conn) bool {
        fmt.Println("After Releasing")
        return true
    }
    config.BeforeAcquire = func(ctx context.Context, conn *pgx.Conn) bool {
        fmt.Println("Before Aquiring")
        return true
    }

    conn, err := pgxpool.ConnectConfig(context.Background(), config)
    s.PoolConn = conn
}

func (s *SqlServerDatabase) PoolPreparedStatementQuery(statement string) { //} (pgx.Rows, error) {
    conn, err := s.PoolConn.Acquire(context.Background())
    fmt.Println("End of PS")
    if err != nil {
        log.Printf("Couldn't get a connection with the database. Reason %v", err)
    } else {
        // release the connection to the pool after using it
        defer conn.Release()

        tx, err := conn.BeginTx(context.Background(), pgx.TxOptions{})
        if err != nil {
            fmt.Println(err)
        }

        if _, err := tx.Prepare(context.Background(), statement, ""); err != nil {
            fmt.Println(err)
        }

        results, err := tx.Query(context.Background(), statement)

        if err != nil {
            log.Printf("Couldn't execute query. Reason %v", err)
        } else {
            // show the results boy, you got it.
            fmt.Printf("%T\n", results)
            fmt.Println("results:", results)
            fmt.Println("Before loop")
            for results.Next() {
                fmt.Println("inside")
                fmt.Println(results.Scan())
            }
        }
    }
    fmt.Println("End of PS")
}

Im pretty new to Go and hadnt even heard of prepared statements until yesterday so please bear with me. I create a connection in ConnectPool. Then in PoolPreparedStatement I try to execute the prepared statement. I am calling it like:

db.PoolPreparedStatementQuery("EXECUTE test_ps")

where test ps is a prepared statement i created on my postgresql database and was able to execute with that command.

I call BeginTx cos Prepare is only on the Tx class. Im not sure i need to do that though? The documentation says Prepare is used to create a prepared statement but i dont need to create it, just execute it. It says it doesnt matter if you call it on an existing statement though so i guess it doesnt matter. When I execute the prepared statement and try and loop through the results there are none. So im not sure what im doing wrong.

0 Answers
Related