在Go中为PGSQL函数提供参数

huangapple go评论88阅读模式
英文:

Providing Arguments for PGSQL Functions in Go

问题

我正在尝试使用db.QueryRow()函数将参数传递给以下的Golang函数,但它似乎不接受通常的问号(?)。

DROP FUNCTION IF EXISTS upsertplatform(pToken varchar);
CREATE FUNCTION upsertplatform(pToken varchar) RETURNS int as $$
    DECLARE
        _id int = NULL;
    BEGIN
        LOOP
            UPDATE public.platform SET platformToken = pToken WHERE userID = 3 AND platformID = 2 RETURNING id into _id;
            IF NOT FOUND THEN
                BEGIN
                    INSERT INTO public.platform (userID, platformID, platformToken) VALUES (3, 2, '1234-123-bbasd') RETURNING id into _id;
                EXCEPTION WHEN unique_violation THEN
                        UPDATE public.platform SET platformToken = '1234-123-bbasd' WHERE userID = 3 AND platformID = 2 RETURNING id into strict _id;
                END;
            END IF;
        EXIT WHEN _id IS NOT NULL;
        END LOOP;
    RETURN 1;
    END
$$ LANGUAGE PLPGSQL;

我在以下查询中遇到了问题,我不确定如何正确地传递参数:

res := db.QueryRow(`SELECT * FROM upsertplatform( ? )`, "test123")

请问我应该如何正确地做这个?

英文:

I am attempting to pass arguments to the following function in Golang with db.QueryRow(), however it doesn't seem to accept the usual ?.

DROP FUNCTION IF EXISTS upsertplatform(pToken varchar);
CREATE FUNCTION upsertplatform(pToken varchar) RETURNS int as $$
	DECLARE
		_id int = NULL;
	BEGIN
		LOOP
			UPDATE public.platform SET platformToken = pToken WHERE userID = 3 AND platformID = 2 RETURNING id into _id;
			IF NOT FOUND THEN
				BEGIN
					INSERT INTO public.platform (userID, platformID, platformToken) VALUES (3, 2, '1234-123-bbasd') RETURNING id into _id;
				EXCEPTION WHEN unique_violation THEN
						UPDATE public.platform SET platformToken = '1234-123-bbasd' WHERE userID = 3 AND platformID = 2 RETURNING id into strict _id;
				END;
			END IF;
		EXIT WHEN _id IS NOT NULL;
		END LOOP;
	RETURN 1;
	END
$$ LANGUAGE PLPGSQL;

This is the query I am having issues with, I'm unsure how to pass arguments to it:

res := db.QueryRow(`SELECT * FROM upsertplatform( ? )`, "test123")

How do I do this correctly?

答案1

得分: 1

Postgres驱动程序使用位置表示法来表示参数,$1,$2,...所以只需使用SELECT * FROM upsertplatform($1)

英文:

The Postgres drivers use positional notation for parameters, $1, $2,... So just SELECT * FROM upsertplatform($1).

huangapple
  • 本文由 发表于 2014年8月12日 13:15:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/25256615.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定