-- メーカーテーブル更新
-- DROP FUNCTION f_maker_update(kubun int4, code int4, shopdv int4, name "varchar", kana "varchar", comm "varchar", recdv int4, usr "varchar", pc "varchar", count int4);


CREATE OR REPLACE FUNCTION f_maker_update(
    kubun       int4,
    code        int4,
    shopdv       int4,
    name        "varchar",
    kana        "varchar",
    comm        "varchar",
    recdv       int4,
    usr         "varchar",
    pc          "varchar",
    count       int4)
RETURNS int4 AS
$$
DECLARE
    cntcheck integer;
BEGIN
    --
    -- パラメータチェック
    --

    -- 処理区分
    IF kubun IS NULL OR kubun NOT IN (1,2,3) THEN
        RAISE EXCEPTION '処理区分が不正です';
    END IF;

    -- 区分
    IF shopdv IS NULL OR shopdv NOT IN (1,2) THEN
        RAISE EXCEPTION '区分が不正です';
    END IF;

    -- 必須チェック
    IF kubun IN (1,2) THEN
        IF recdv IS NULL THEN
            RAISE EXCEPTION '引数 recdv は必須です';
        END IF;
    END IF;
    IF kubun IN (2,3) THEN
        IF code IS NULL THEN
            RAISE EXCEPTION '引数 code は必須です';
        END IF;
        IF count IS NULL THEN
            RAISE EXCEPTION '引数 count は必須です';
        END IF;
    END IF;

    -- 桁数チェック
    IF kubun IN (1,2) THEN
        IF s_check_length(name, 256) = FALSE THEN
            RAISE EXCEPTION '引数 name が不正です';
        END IF;
        IF s_check_length(kana, 256) = FALSE THEN
            RAISE EXCEPTION '引数 kana が不正です';
        END IF;
        IF s_check_length(comm, 1024) = FALSE THEN
            RAISE EXCEPTION '引数 comm が不正です';
        END IF;
    END IF;
    IF kubun IN (1,2,3) THEN
        IF s_check_upd(usr, pc) = FALSE THEN
            RAISE EXCEPTION '引数 usr&pc が不正です';
        END IF;
    END IF;

    -- 品目基本属性チェック
    IF kubun IN (3) THEN
        SELECT itemcd INTO cntcheck FROM t_item_basic_attr WHERE shopdiv = shopdv AND makercd = code AND delflg = false;
        IF FOUND THEN
            RETURN -10;
        END IF;
    END IF;

    -- 更新カウンタチェック
    IF kubun IN (2,3) THEN
        SELECT updcnt INTO cntcheck FROM t_maker WHERE makercd = code;
          IF NOT FOUND OR cntcheck <> count THEN
            RETURN -11;
        END IF;
    END IF;

    --
    -- 更新処理
    --

    -- 追加
    IF kubun = 1 THEN
        INSERT INTO t_maker(makernm, makernmkana, comment, recommenddiv, shopdiv, updusrnm, updpcnm)
               VALUES(name, kana, comm, recdv, shopdv, usr, pc);

    -- 更新
    ELSIF kubun = 2 THEN
        UPDATE t_maker
           SET makernm = name,
               makernmkana = kana,
               comment = comm,
               recommenddiv = recdv,
               updusrnm = usr,
               updpcnm = pc
         WHERE makercd = code AND shopdiv = shopdv;

    -- 削除
    ELSIF kubun = 3 THEN
        UPDATE t_maker
           SET delflg = TRUE,
               updusrnm = usr,
               updpcnm = pc
         WHERE makercd = code AND shopdiv = shopdv;
    END IF;

    RETURN 1;
END;
$$
LANGUAGE 'plpgsql' VOLATILE;

