Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

МиСПрИС_Задание3_Петрова_Романова_Заболотников_9373

.docx
Скачиваний:
15
Добавлен:
20.06.2023
Размер:
2.07 Mб
Скачать

on delete cascade -- Если удаляется объект перечисления, то удалятся и все значения, которые на него ссылались

)

--Добавили нобходимые внешние ключи

ALTER TABLE product_parameters ADD CONSTRAINT id_enum_value FOREIGN KEY (id_enum_value)

REFERENCES enum_value(id_value) MATCH simple -- Ограничение для ссылки только на существующее id

ON UPDATE NO action --На обновление таблицы перечисления нет реакции

ON DELETE cascade; -- Если удаляется объект перечисления, то удалятся и все значения, которые на него ссылались

ALTER TABLE product_parameters ADD CONSTRAINT id_prod FOREIGN KEY (id_prod)

REFERENCES product(id_product ) MATCH simple -- Ограничение для ссылки только на существующее id

ON UPDATE NO action --На обновление таблицы перечисления нет реакции

ON DELETE cascade; -- Если удаляется объект перечисления, то удалятся и все значения, которые на него ссылались

drop table product_parameters;

-------------Функции--------------------------------------------------------------

-- Ограниччение имени класса

-- Добавление нового класса

CREATE OR REPLACE function add_class (

nameOfNewClass text,

parentOfNewClass integer,

uomOfNewClass integer) RETURNS int

as $$

declare ind_class int default 0;

declare ind_uom int default 0;

declare ind_name int default 0;

begin

select id_class from product_class where parentOfNewClass = id_class into ind_class;

select id_uom from unit_of_measure where uomOfNewClass = id_uom into ind_uom;

select id_class from product_class where nameOfNewClass = name_class into ind_name;

-- raise notice 'ind_name: %', ind_name;

if ind_class is not null or (ind_class isnull and parentOfNewClass isnull) then

if ind_uom is not null then

if ind_name is null then

INSERT INTO Product_class(name_class, parent_class_id, id_uom) VALUES ($1, $2, $3);

return 1;

else

raise notice 'The class with this name already exists. DB was not updated.';

return 0;

end if;

else

raise notice 'This iduom is not existing. Db was not updated.';

return 0;

end if;

else

raise notice 'This idClass for parent is not existing. Db was not updated.';

return 0;

end if;

end $$ LANGUAGE plpgsql;

--select delete_class(18)

-- Добавление элементов в таблицу UOM

CREATE OR REPLACE function add_uom (

shortNameOfNewUOM text,

fullNameOfNewUOM text ) RETURNS int

as $$

declare ind int default null;

begin

select id_uom from unit_of_measure where fullNameOfNewUOM = name_uom and shortNameOfNewUOM = short_name_uom into ind;

if ind is not null then

raise notice 'This uom already exists. DB was not updated';

return 0;

else

INSERT INTO Unit_of_Measure(short_name_uom, name_uom) VALUES ($1, $2);

return 1;

end if;

end $$ LANGUAGE plpgsql;

-- Удаление элементов из таблицы UOM

CREATE OR REPLACE function add_uom (

id_delete int ) RETURNS int

as $$

declare ind int default null;

begin

select id_uom from unit_of_measure where id_delete = id_uom into ind;

if ind is not null then

delete from Unit_of_Measure where id_uom = id_delete;

return 1;

else

raise notice 'This uom does not exist. DB was not updated';

return 0;

end if;

end $$ LANGUAGE plpgsql;

--Добавление продукта

CREATE OR REPLACE function add_product (

nameOfNewProduct text,

idClassOfNewProduct integer ) RETURNS int

as $$

declare ind int default 0;

begin

select id_class from product_class where id_class = idClassOfNewProduct into ind;

if ind is not null then

if check_term(idClassOfNewProduct) is null then

INSERT INTO product(name_product, id_class) VALUES ($1, $2);

return 1;

else

raise notice 'Parent class is not terminal. DB wasnt updated.';

return 0;

end if;

else

raise notice 'Parent class is not existing. DB wasnt updated.';

return 0;

end if;

end $$ LANGUAGE plpgsql;

--select add_product('Держи марку!', 2);

--select delete_product(13);

--Смена родителя класса

CREATE OR REPLACE function change_parent_class (

idClassForSet integer,

idNewClassParent integer) RETURNS int

as $$

declare old_class int;

declare ind_class int default 0;

begin

select id_class from product_class where id_class = idNewClassParent into ind_class;

if ind_class is not null then

select parent_class_id from product_class where id_class = idClassForSet into old_class;

UPDATE Product_Class SET parent_class_id = idNewClassParent WHERE id_class = idClassForSet;

if check_loops(idClassForSet) != 0 then

raise notice 'You have created the loop. DB wasnt updated.';

UPDATE Product_Class SET parent_class_id = old_class WHERE id_class = idClassForSet;

return 0;

else

return 1;

end if;

else

raise notice 'Parent class is not existing. DB wasnt updated.';

return 0;

end if;

end $$ LANGUAGE plpgsql;

--Смена класса продукта

CREATE OR REPLACE function change_product_class (

idProductForSet integer,

newClassForProduct integer) RETURNS int

as $$

declare ind_class int default 0;

begin

select id_class from product_class where id_class = newClassForProduct into ind_class;

if ind_class is not null then

if check_term(newClassForProduct) is null then

UPDATE Product SET id_class = newClassForProduct WHERE id_product = idProductForSet;

return 1;

else

raise notice 'New parent is not terminal class. DB wasnt updated.';

return 0;

end if;

else

raise notice 'Parent class is not existing. DB wasnt updated.';

return 0;

end if;

end $$ LANGUAGE plpgsql;

--Удаление класса из классификатора

CREATE OR REPLACE function delete_class (

ClassIdToDelete integer) RETURNS int

as $$

declare ind int default 0;

begin

select id_class from product_class where id_class = ClassIdToDelete into ind;

if ind is not null then

DELETE FROM Product_Class WHERE id_class = ClassIdToDelete;

return 1;

else

raise notice 'The class does not exist.DB was not updated.';

return 0;

end if;

end $$ LANGUAGE plpgsql;

--Удаление продукта

CREATE OR REPLACE function delete_product (

ProductIdToDelete integer) RETURNS int

as $$

declare ind int default 0;

begin

select id_product from product where id_product = ProductIdToDelete into ind;

if ind is not null then

DELETE FROM Product WHERE id_product = ProductIdToDelete;

return 1;

else

raise notice 'The product does not exist.DB was not updated.';

return 0;

end if;

end $$ LANGUAGE plpgsql;

--Просмотр подграфа

CREATE OR REPLACE function showtree(INTEGER)

RETURNS table (id_class integer, name_class text, name_product text) as $$

begin

RETURN QUERY

WITH RECURSIVE tab1 (id_class, parent_class_id, name_class, path) AS (

SELECT t1.id_class, t1.parent_class_id, t1.name_class, CAST (t1.name_class AS TEXT) as PATH

FROM Product_Class t1 WHERE t1.id_class=$1

union

SELECT t2.id_class, t2.parent_class_id, t2.name_class, CAST ( tab1.PATH ||' = > '|| t2.name_class AS TEXT)

FROM Product_Class t2 INNER JOIN tab1 ON( tab1.id_class = t2.parent_class_id) )

SELECT c.id_class, c.path, p.name_product as name_product

FROM tab1 as c LEFT JOIN Product as p on c.id_class=p.id_class

ORDER BY path, p.name_product;

end;

$$ LANGUAGE plpgsql;

-- Проверка на цикл

CREATE OR REPLACE function check_loops(INTEGER) returns integer

as $$

declare ind int default 0;

declare stage_i int default $1;

declare rem int default $1;

declare i int default 0;

begin

while i < 10 loop

select parent_class_id from product_class where stage_i = id_class into stage_i;

if rem = stage_i then

ind:= ind + 1;

end if;

i:= i + 1;

end loop;

return ind;

end $$ LANGUAGE plpgsql;

-- Вывод родителей

CREATE OR REPLACE function show_parent(id_class_sh INTEGER) returns table (deep int, id_class_prnt int, name_class_prnt text)

as $$

declare name_class_prnt text;

declare id_class_prnt text;

declare mem int default id_class_sh;

declare deep int default 0;

declare prnt int default 0;

begin

select parent_class_id from product_class where mem = id_class into prnt; --Для входа в цикл

while prnt is not null loop

return query select deep as deep, id_class , name_class from product_class where mem = id_class;

deep:= deep + 1;

select parent_class_id from product_class where mem = id_class into mem; -- Сменим текущую позицию на позицию родителя

select parent_class_id from product_class where mem = id_class into prnt; -- Занесём в переменную значение родителя новой позиции

end loop;

return query select deep as deep, id_class, name_class from product_class where mem = id_class;

end $$ language plpgsql;

select deep, id_class_prnt, name_class_prnt from show_parent(6);

-- Вывод потомков

CREATE OR REPLACE function show_children(INTEGER)

RETURNS table (id_class integer, name_class text, name_product text) as $$

begin

RETURN QUERY

WITH RECURSIVE tab1 (id_class, parent_class_id, name_class) AS (

SELECT t1.id_class, t1.parent_class_id, t1.name_class

FROM Product_Class t1 WHERE t1.id_class=$1

union

SELECT t2.id_class, t2.parent_class_id, t2.name_class

FROM Product_Class t2 INNER JOIN tab1 ON( tab1.id_class = t2.parent_class_id) )

SELECT c.id_class, c.name_class, p.name_product as name_product

FROM tab1 as c LEFT JOIN Product as p on c.id_class=p.id_class

where c.id_class != $1

ORDER BY p.name_product;

end;

$$ LANGUAGE plpgsql;

-- Проверка терминального класса при добавлении продукта

CREATE OR REPLACE function check_term(idClassParentForSet INTEGER) returns integer

as $$

declare ind int default 0;

begin

select id_class from product_class where parent_class_id = idClassParentForSet into ind;

return ind;

end $$ LANGUAGE plpgsql;

--Создание перечисления

CREATE OR REPLACE function add_enum (

new_enum_name text)

RETURNS int

/*функция: Создание перечисления

вход: new_enum_name - Имя перечисления

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если уже существует перечисление с таким именем, то перечисление не создаётся.

*/

as $$

declare ind int default 0;

begin

select id_enum from enumeration where new_enum_name = name_enum into ind;

if ind is not null then

raise notice 'Enumeration with this name already exists. Db was not updated';

ind:=0;

return ind;

else

INSERT INTO enumeration(name_enum) VALUES ($1);

ind:= 1;

return ind;

end if;

end $$ LANGUAGE plpgsql;

--Удаление перечисления

CREATE OR REPLACE function delete_enum (

delete_id integer) RETURNS int

/*функция: Удаление перечисления

вход: delete_id - Id перечисления, которое надо удалить

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если перечисления с таким id нет, то БД не обновится и будет выведена ошибка

*/

as $$

declare ind int default 0;

begin

select id_enum from enumeration where delete_id = id_enum into ind;

if ind is not null then

DELETE FROM enumeration WHERE id_enum = delete_id;

ind:= 1;

return ind;

else

raise notice 'Enumeration with this id does not exist. Db was not updated';

ind:= 0;

return ind;

end if;

end $$ LANGUAGE plpgsql;

-- Добавление значения в перечисление

create or replace function add_value (

new_value_name text,

new_id_enum integer

)

returns int

/*функция: Добавление значения в перечисление

вход: new_value_name - имя значения, которое будет добавлено

new_id_enum - id перечисления, к которому добавлеяется значение

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если перечисления с таким id нет, то БД не обновится и будет выведена ошибка

2. Если такое значение уже есть в перечислении, то оно добавлено не будет

*/

as $$

declare new_num integer;

declare ind_id int default 0;

declare ind_rep int default 0;

begin

select id_enum from enumeration where new_id_enum = id_enum into ind_id;

select id_value from enum_value where name_value = new_value_name and id_enum = new_id_enum into ind_rep;

if ind_id is null then

raise notice 'This enumerator does not exist. DB was not updated.';

return 0;

else

if ind_rep is not null then

raise notice 'This value already exists in this enumeration.DB was not updated.';

return 0;

else

if ((select COUNT(*) from enum_value where id_enum = $2) = 0) then--Если в перечислении ещё нет значений,

--то порядковый номер значения будет 1

new_num:= 1;

else

select MAX(num)+1 from enum_value where id_enum = $2 into new_num;

end if;

insert into enum_value(num, name_value, id_enum) VALUES (new_num, $1, $2);

return 1;

end if;

end if;

end $$ LANGUAGE plpgsql;

-- Удаление значения из перечисления

CREATE OR REPLACE function delete_enum_value (

delete_id integer) RETURNS int

/*функция: Удаления значения из перечисления

вход: delete_id - id значения, которое будет удалено

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если значения с таким id нет, то БД не обновится и будет выведена ошибка

*/

as $$

declare ind int default 0;

declare idEnum int default 0;

declare numd int default 0;

begin

select id_value, num, id_enum from enum_value where id_value = delete_id into ind, numd, idEnum;

if ind is not null then

update enum_value set num = num-1 where num> numd and id_enum = idEnum;

DELETE FROM enum_value WHERE id_value = delete_id;

return 1;

else

raise notice 'The value with this id does not exist.DB was not updated.';

return 0;

end if;

end $$ LANGUAGE plpgsql;

-- Найти список значений перечисления

CREATE OR REPLACE function show_enum_value(idEnum integer)

RETURNS table (idValueResault integer, NumResault integer, NameResault text, idEnumResault integer)

/*функция: Перечисления значений для заданного перечисления

вход: idEnum- id значения, которое будет удалено

выход: Таблица с найденными значениями

эффекты: 1. Если перечисления с таким id нет, то будет выведена ошибка

*/

as $$

declare ind int default 0;

begin

select id_enum from enumeration where id_enum = idEnum into ind;

if ind is not null then

return query select * from enum_value where id_enum = $1;

else

raise notice 'The value with this id does not exist.';

return query select 0,0,'0',0;

end if;

end;

$$ language plpgsql;

--DROP FUNCTION show_enum_value(integer)

-- Переназначение порядкового номера значения в перечислении

create or replace function set_num_value (idValue integer,new_num integer) returns int

/*функция: Переназначения порядкового номера значения в перечислении

вход: idValue - id значения, для которого переназначается порядковый номер

new_num - значение нового порядкового номера

выход: 1 - БД обновлена успешно, 0 - Ошибка

эффекты: 1. Если не существует значения по заданному id, то будет выведена ошибка

2. Если Порядковый номер меньше 1, то он устанавливается в 1.

3. Если порядковый номер больше максимального, то он устанавливается в максимальный

*/

as $$

declare max_num integer;

declare old_num integer;

declare id_enumm integer;

declare ind int default 0;

begin

select id_value from enum_value where id_value = idValue into ind;

if ind is not null then

select num from enum_value where id_value = idValue into old_num; -- Узнаем старый порядковый номер

select id_enum from enum_value where id_value = idValue into id_enumm; -- Узнаем id перечисления значения

select MAX(num) from enum_value where id_enum = id_enumm into max_num; --Узнаём максимальный порядковый номер в этом перечислении

if new_num > max_num then

new_num = max_num;

end if;

if new_num < 1 then

new_num = 1;

end if;

if (new_num > old_num)

then

update enum_value set num = new_num where id_value = idValue;

update enum_value set num = num - 1 where id_enum = id_enumm and num > old_num and num <=new_num and id_value <> idValue;

else

update enum_value set num = new_num where id_value = idValue;

update enum_value set num = num + 1 where id_enum = id_enumm and num < old_num and num >= new_num and id_value <> idValue;

end if;

return 1;

else

raise notice 'The value with this id does not exist.';

return 0;

end if;

end $$ language plpgsql;

-----------------------------------------------------------------Функции -----------------------------------------------------------------

--Добавление типа параметра

CREATE OR REPLACE function add_type (

new_type_name text)

RETURNS int

/*функция: Создание типа параметра

вход: new_enum_name - Имя типа

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если уже существует тип с таким именем, то он не создаётся.

*/

as $$

declare ind int default 0;

begin

select id_type from parameter_type where new_type_name = name_type into ind;

if ind is not null then

raise notice 'Type with this name already exists. Db was not updated';

return 0;

else

INSERT INTO parameter_type(name_type) VALUES (new_type_name);

return 1;

end if;

end $$ LANGUAGE plpgsql;

--Удаление типа

CREATE OR REPLACE function delete_type (

delete_id integer) RETURNS int

/*функция: Удаление типа

вход: delete_id - Id типа, которое надо удалить

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если типа с таким id нет, то БД не обновится и будет выведена ошибка

*/

as $$

declare ind int default 0;

begin

select id_type from perameter_type where delete_id = id_type into ind;

if ind is not null then

DELETE FROM perameter_type WHERE id_type = delete_id;

return 1;

else

raise notice 'Type with this id does not exist. Db was not updated';

return 0;

end if;

end $$ LANGUAGE plpgsql;

---Функция добавление аггрегата

CREATE OR REPLACE function add_agg (

idAgg int, idPar int)

RETURNS int

/*функция: Создание связи аггрегата с параметром

вход: idAgg - id параметра-аггрегата

idPar - id парамета, входящего в этот агрегат

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если уже существует заданная пара типа аггрегат - параметр, то ф-ия выдаст ошибку.

2. Если id не существуют, то ф-ия также выдаст ошибку.

3. Если idAgg имеет значение параметра не типа аггрегат также будет выведена ошибка.

*/

as $$

declare ind_agg int default 0;

declare new_num int default 0;

begin

--Проверка на тип параметра idAgg

select id_type from parameters where id_parameter = idAgg into ind_agg;

if ind_agg is not null then

if (select name_type from parameter_type where ind_agg = id_type) = 'Агрегат' then

if(select id_type from parameters where id_parameter = idPar) is not null then

if(select id_link from aggregate_position where id_par = idPar and agg_par = idAgg) is null then

if ((select COUNT(*) from aggregate_position where agg_par = idAgg) = 0) then--Если в перечислении ещё нет значений,

--то порядковый номер значения будет 1

new_num:= 1;

else

select MAX(num)+1 from aggregate_position where agg_par = idAgg into new_num;

end if;

insert into aggregate_position(agg_par, id_par, num) values (idAgg,idPar, new_num);

return 1;

else

raise notice 'This idPar and idAgg already exist. DB was not updated.';

return 0;

end if;

else

raise notice 'This idPar does not exist. DB was not updated.';

return 0;

end if;

else

raise notice 'This idAgg is not aggregat parameter. DB was not updated.';

return 0;

end if;

else

raise notice 'This idAgg does not exist. DB was not updated.';

return 0;

end if;

end $$ LANGUAGE plpgsql;

--Удаление аггрегата параметра

CREATE OR REPLACE function delete_agg (

idPar integer, idAgg integer) RETURNS int

/*функция: Удаление связи агрегата с параметром

вход: idPar - id параметра, который будет удалён из агрегата

idAgg - id агрегата, для которого удалится параметр

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если значения с таким id нет, то БД не обновится и будет выведена ошибка

*/

as $$

declare numd int default 0;

begin

select num from aggregate_position where agg_par = idAgg and id_par = idPar into numd;

if (numd) is not null then

update aggregate_position set num = -(num-1) where num> numd and agg_par = idAgg;

DELETE FROM aggregate_position WHERE agg_par = idAgg and id_par = idPar;

update aggregate_position set num = -num where num<0;

return 1;

else

raise notice 'The value with this ids does not exist.DB was not updated.';

return 0;

end if;

end $$ LANGUAGE plpgsql;

--Добавление параметров класса

CREATE OR REPLACE function add_class_parameters (

idClass int, idPar int, inmaximum int, inminimum int)

RETURNS int

/*функция: Создание свзяи между классом и параметром

вход: idClass - id класса

idPar - id параметра

maximum - максимальное значеие параметра

minimum - минимальное значение параметра

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если уже существует такая пара класс-параметр, то связь не создаётся.

2. Если параметров с введёнными id нет, то свзяь тоже не создается.

*/

as $$

declare ind int default 0;

begin

select id_link from class_parameters where idClass = id_class and id_par = idPar into ind;

if ind is not null then

raise notice 'Pair with this ids already exists. Db was not updated';

return 0;

else

if (select id_class from product_class where id_class = idClass) is not null then

if (select id_parameter from parameters where id_parameter = idPar) is not null then

INSERT INTO class_parameters(id_par, id_class, maximum, minimum) VALUES (idPar, idClass, inmaximum , inminimum);

return 1;

else

raise notice 'Parameter with this id does not exists. Db was not updated';

return 0;

end if;

else

raise notice 'Class with this id does not exists. Db was not updated';

return 0;

end if;

end if;

end $$ LANGUAGE plpgsql;

--Удаление параметров класса

CREATE OR REPLACE function delete_class_parameters (

idClass int, idPar int) RETURNS int

/*функция: Удаление параметра класса

вход: idClass - id класса

idPar - id параметра

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если пары с такими id нет, то БД не обновится и будет выведена ошибка

*/

as $$

declare ind int default 0;

begin

select id_link from class_parameters where id_par = idPar and id_class = idClass into ind;

if ind is not null then

DELETE FROM class_parameters WHERE id_link = ind;

return 1;

else

raise notice 'Pair with this ids does not exist. Db was not updated';

return 0;

end if;

end $$ LANGUAGE plpgsql;

---Добавление в таблицу параметров продукта

--Функция проверки значения параметра для продукта

CREATE OR REPLACE function check_maxMin (

idProd int, idPar int, value int )

RETURNS int

/*функция: Проверка ограничения

вход: idProd - id продукта

idPar - id параметра

value - числнное значение параметра

выход: 1 - значение подходит, 0 - Не подходит

эффекты: 1. Если продукт не существует, то возвращается 0 и ошибка выводится.

*/

as $$

declare idClass int default 0;

declare maxim int default 0;

declare minim int default 0;

begin

select id_class from product where id_product = idProd into idClass;

if idClass is null then

raise notice 'Product with this id does not exist!';

return 0;

else

select maximum, minimum from class_parameters where id_class = idClass and id_par = idPar into maxim, minim;

if value <= maxim and value >= minim then

return 1;

else

return 0;

end if;

end if;

end $$ LANGUAGE plpgsql;

--Создание связи между продуктом и праметром

CREATE OR REPLACE function add_product_parameters (

idProd int, idPar int, value int default null, id_enum_value int default null, numAgg integer default null)

RETURNS int

/*функция: Создание свзяи между продуктом и параметром

вход: idProd - id продукта

idPar - id параметра

value - числнное значение параметра

id_enum_value - id значения перечисления параметра

numAgg - порядковый номер параметра в агргате (вводится только если параметр - часть агрегата)

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если все параметры агрегата уже заполнены, то БД выдаст ошибку.

2. Если ведены неправильно параметры в функцию (например, и число и перечисление), то БД выдаст ошибку.

3. Если численное зачение не подходит под ограничения класса, то БД выведет ошибку.

4. Если этот параметр для данного продукта уже есть (и параметр не Авторы и не Переводчики), то

БД выдаст ошибку.

*/

as $$

declare count_pars int default 0;

declare onlyOne int default 0;

declare buf int;

begin

--Необходимо, чтобы было заполнено одно из 3х последних полей, поэтому устанавливаем ограничение

if value is not null then

onlyOne:= onlyOne + 1;

end if;

if id_enum_value is not null then

onlyOne:= onlyOne + 1;

end if;

if numAgg is not null then

onlyOne:= onlyOne + 1;

end if;

if onlyOne != 1 then

if value is not null and numAgg is not null then

select count(*) from aggregate_position where agg_par = idPar into count_pars;

if (select count(*) from product_parameters where id_par = idPar and id_prod = idProd) = count_pars then

raise notice 'This aggregate parameter for this product is full already. DB was not updated.';

return 0;

else

if(select check_maxMin(idProd, idPar, value)) is not null then

insert into product_parameters(id_par, id_prod, value, num_agg) values (idPar, idProd, value, numAgg);

return 1;

end if;

end if;

elsif id_enum_value is not null and numAgg is not null then

select count(*) from aggregate_position where agg_par = idPar into count_pars;

if (select count(*) from product_parameters where id_par = idPar and id_prod = idProd) = count_pars then

raise notice 'This aggregate parameter for this product is full already. DB was not updated.';

return 0;

else

insert into product_parameters(id_par, id_prod, id_enum_value, num_agg) values (idPar, idProd,id_enum_value, numAgg);

return 1;

end if;

else

end if;

raise notice 'You should enter 1 of three last parameters of functon.';

return 0;

else

if value is not null then --Если численное значение

if (select id_link from product_parameters where id_par = idPar and id_prod = idProd) is not null then

raise notice 'This parameter for this product already exists. DB was nor updated';

return 0;

else

if(select check_maxMin(idProd, idPar, value)) is not null then

insert into product_parameters(id_par, id_prod, value) values (idPar, idProd, value);

return 1;

end if;

end if;

elsif id_enum_value is not null then

select id_link from product_parameters where id_par = idPar and id_prod = idProd and idPar not in (

select id_parameter from parameters where name_parameter = 'Авторы' or name_parameter = 'Переводчики') limit 1 into buf;

if (buf) is not null then

raise notice 'This parameter for this product already exists. DB was nor updated';

return 0;

else

insert into product_parameters(id_par, id_prod, id_enum_value) values (idPar, idProd, id_enum_value);

return 1;

end if;

end if;

end if;

end $$ LANGUAGE plpgsql;

;

--Удаление строки из таблицы параметров продуктов

CREATE OR REPLACE function delete_product_parameters (

idProd int, idPar int)

RETURNS int

/*функция: Удаления строки из таблицы параметров продуктов

вход: idProd - id продукта

idPar - id параметра

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если нет такого параметра для продукта, то выводится ошибка.

*/

as $$

begin

if (select id_link from product_parameters where id_prod = idProd and id_par = idPar limit 1) is not null then

delete from product_parameters where id_prod = idProd and id_par = idPar;

return 1;

else

raise notice 'There is not this parameter for inputed product. DB was not updated.';

return 0;

end if;

end $$ LANGUAGE plpgsql;

--Создание параметра

CREATE OR REPLACE function add_parameter(

namePar text, idType int, uomPar int default null, idEnum int default null)

RETURNS int

/*функция: Создание параметра

вход: namePar - имя параметра

idType - тип параметра

uomPar - единица измерения

idEnum - id перечисления

выход: 1 - БД обновлена, 0 - Ошибка

эффекты: 1. Если есть параметр с таким именем - ошибка;

2. Если нет единицы измерения, на которую ссылается параметр - ошибка;

3. Если нет типа, на который ссылается параметр - ошибка;

4. Если нет типа перечисления, на который ссылается параметр - ошибка;