我有一组创建表和函数等的Sqitch迁移,但是,我也需要用我的应用程序所需的基本数据集为我的数据库添加种子。
然而,有些种子需要来自先前创建的种子的Ids。例如,我有一个创建Post的函数和一个注释的函数,在我创建了一个Post之后,我需要创建引用Post Id的注释。
我的post_create函数如下所示:
BEGIN;
CREATE FUNCTION post_create(
_title TEXT,
_body TEXT
)
RETURNS SETOF post_type
LANGUAGE plpgsql
AS $$
BEGIN
RETURN QUERY (
WITH _created_post AS (
INSERT INTO "post" (
"title",
"body"
"created_at"
)
VALUES (
_title,
_body,
ROUND(EXTRACT(EPOCH FROM now()))
)
RETURNING
*
)
SELECT
*
FROM
_created_post
);
END;
$$;
COMMIT;我的comment_create函数看起来很相似,如下所示:
BEGIN;
CREATE FUNCTION comment_create(
_post_id INTEGER,
_body TEXT
)
RETURNS SETOF comment_type
LANGUAGE plpgsql
AS $$
BEGIN
RETURN QUERY (
WITH _created_comment AS (
INSERT INTO "comment" (
"post_id",
"body"
"created_at"
)
VALUES (
_post_id,
_body,
ROUND(EXTRACT(EPOCH FROM now()))
)
RETURNING
*
)
SELECT
*
FROM
_created_comment
);
END;
$$;
COMMIT;我的种子迁移基本上是一个空白的Sqitch迁移:
-- Deploy my-app:seeds to pg
-- requires: post_create
-- requires: comment_create
BEGIN;
-- Create a post and capture the post Id
-- Create a comment with previously captured post Id
COMMIT;但是,我很难找到正确的语法来使它正常工作。
如何使我的Sqitch迁移脚本调用函数,并在调用其他函数时将结果用作输入?
发布于 2020-06-07 20:44:09
使用匿名函数?:https://www.postgresql.org/docs/12/sql-do.html
DO $$
DECLARE
post post_type;
BEGIN
--Edited to version that Luke created and used.
SELECT * FROM post_create(...) INTO post;
PERFORM comment_create(post.id, 'body text');
END$$;https://stackoverflow.com/questions/61951096
复制相似问题