jackc / pgx

PostgreSQL driver and toolkit for Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't run anonymous SQL functions

vorishirne opened this issue · comments

Describe the bug
this is the sql query that is having issues running.

DO $$ BEGIN 
  UPDATE workers SET email = $2 WHERE id=$1 ;
  IF NOT FOUND THEN 
    INSERT INTO workers (id,email) VALUES ($1,$2) ;
  END IF; 
END $$;

I can run this via psql as expected. But pgx throws error ``

To Reproduce

CREATE TABLE workers(
id SERIAL PRIMARY KEY,
email VARCHAR(255)
);

DO $$ BEGIN 
  UPDATE workers SET email = 'xyz' WHERE id=3 ;
  IF NOT FOUND THEN 
    INSERT INTO workers (id,email) VALUES (3,'xyz') ;
  END IF; 
END $$;

SELECT * FROM workers; 

the row is added, but now in code

package foodata

import (
	"context"
	"github.com/jackc/pgx/v4"
	_ "github.com/jackc/pgx/v4"
	_ "github.com/jackc/pgx/v4/pgxpool"

	"gitlab.private.aws.cradlepointecm.com/netcloud/saas/ncx/service-template/internal/daos"
)

func RunDB() error {

	ctx := context.Background()
	dbPool, err := daos.GetPG1Conn(ctx)

	if err != nil {
		return err
	}
	batch := &pgx.Batch{}
	batch.Queue(`
DO $$ BEGIN 
  UPDATE workers SET email = $2 WHERE id=$1 ;
  IF NOT FOUND THEN 
    INSERT INTO workers (id,email) VALUES ($1,$2) ;
  END IF; 
END $$;
`, 1, "a")
	results := dbPool.SendBatch(ctx, batch)

	_, err = results.Exec()
	if err != nil {
		return err
	}

	err = results.Close()
	if err != nil {
		return err
	}

	return nil
}

Expected behavior
The query must run without error

Actual behavior
msg.ParameterOIDs is empty
I get this error msg mismatched param and argument count

Version

  • Go: $ go version -> [e.g. go version go1.20.6 linux/amd64
  • PostgreSQL: $ psql --no-psqlrc --tuples-only -c 'select version()' -> [ PostgreSQL 15.3 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 7.3.1 20180712 (Red Hat 7.3.1-12), 64-bit
    ]
  • pgx: $ grep 'github.com/jackc/pgx/v[0-9]' go.mod -> [e.g. v4.18.1

Answered here by @jackc
#1686