好吧,所以我有一个函数,类型为JSONB
,并根据来自该数据块的各种键执行SELECT
和INSERT
。 PostgreSQL抛出与PERFORM
和INSERT
有关的错误。在SQL查询中json数据的正确用法是什么?
CREATE OR REPLACE FUNCTION add_revision(d jsonb)
RETURNS jsonb AS $$
DECLARE
did INT;
BEGIN
did:=get_drawing_id(d->>'Name');
IF did=NULL THEN
did:=create_drawing(d->>'Name',d->>'Discipline',
d->>'Doc Type');
END IF;
PERFORM * FROM revisions WHERE drawingid=did AND Sequence=d->>'Sequence';
IF NOT FOUND THEN
INSERT INTO revisions (Sequence,Revision,State,Meta) VALUES(d->>'Sequence',
d->>'Version',d->>'State',d);
RETURN jsonb_build_object('ok',true);
END IF;
RETURN jsonb_build_object('ok',false,'message','Already exists');
END;
$$ LANGUAGE plpgsql;
这是抛出错误的地方
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42883]: Un
defined function: 7 ERROR: operator does not exist: integer = text
LINE 1: ... * FROM revisions WHERE drawingid=did AND Sequence=(d->>'Seq...
答案 0 :(得分:1)
您不能将整数与文本进行比较。 PostgreSQL是严格的。
在此部分检查类型。
drawingid=did AND Sequence=d->>'Sequence'
这应该不是与JSONB相关的问题。
答案 1 :(得分:0)
在查询中使用JSONB函数非常好,我只需要将类型转换为所需的类型:
CREATE OR REPLACE FUNCTION add_drawing_revision(d jsonb)
RETURNS jsonb AS $$
DECLARE
did INT;
BEGIN
did:=get_drawing_id(d->>'Name');
IF did<0 THEN
did:=create_drawing(d->>'Name',d->>'Discipline',
d->>'Doc Type');
END IF;
PERFORM * FROM revisions WHERE drawingid=did AND Sequence=(d->>'Sequence')::INT;
IF NOT FOUND THEN
INSERT INTO revisions (Sequence,Revision,State,Meta) VALUES((d->>'Sequence')::INT,
d->>'Version',d->>'State',d);
RETURN jsonb_build_object('ok',true);
END IF;
RETURN jsonb_build_object('ok',false,'message','Already exists');
END;
$$ LANGUAGE plpgsql;