0

есть функция

DROP FUNCTION IF EXISTS create_post;

CREATE FUNCTION create_post(
    txt text,
    created BIGINT,
    photourl text,
    user_id bigint
) RETURNS TABLE(
    id bigint,
    "text" text,
    created_at timestamp,
    photo_url text,
    user_email text,
    comments_count int
) AS $$
DECLARE ret_id bigint;

BEGIN
INSERT INTO posts(
        "text",
        created_at,
        photo_url,
        user_id
    )
VALUES ($1, to_timestamp($2), $3, $4)
RETURNING posts.id INTO ret_id;

RETURN query
SELECT p.id AS id,
    p.text AS "text",
    p.created_at AS created_at,
    p.photo_url AS photo_url,
    u.email AS user_email,
    COUNT(c) AS comments_count
FROM posts AS p
    INNER JOIN users AS u ON u.id = p.user_id
    LEFT JOIN comments AS c ON c.post_id = p.id
WHERE p.id = ret_id
GROUP BY p.id,
    u.email;

END $$ LANGUAGE plpgsql;

Она создаётся нормально, но при вызове SELECT create_post('haha', 1652131509, 'photo', 2); получаю ошибку structure of query does not match function result type. Типы и имена столбцов вроде совпадают. Другие таблицы:

CREATE TABLE "users" (
    "id" BIGSERIAL PRIMARY KEY,
    "email" text UNIQUE NOT NULL,
    "encrypted_password" text NOT NULL,
    "created_at" timestamp NOT NULL
);

CREATE TABLE "posts" (
    "id" BIGSERIAL PRIMARY KEY,
    "text" text,
    "created_at" timestamp NOT NULL,
    "photo_url" text,
    "user_id" bigint NOT NULL,
    FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE
);
2
  • SELECT * FROM create_post('haha', 1652131509, 'photo', 2) x;?
    – Akina
    10 мая 2022 в 13:08
  • уже решил проблему 10 мая 2022 в 13:24

1 ответ 1

0

count(*) возвращает BIGINT, а не просто INT

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.