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

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

.pdf
Скачиваний:
23
Добавлен:
20.06.2023
Размер:
1.3 Mб
Скачать

select id_order from pos_order where oIdProduct = id_prod and oIdOrder = id_order into ind_rep; --Проверка повторного внесения продукта в заказ

if oq <= 0 then

raise notice 'Q can not be less or equal 0'; return 0;

else

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 id_order from pos_order where oIdOrder = id_order) is null) then--Если в перечислении ещё нет значений,

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

else

select MAX(num)+1 from pos_order where oIdOrder = id_order into new_num;

end if;

insert into pos_order(id_order, id_prod, num, q) VALUES ($1, $2, new_num, $3);

return 1; end if;

end if; end if;

end $$ LANGUAGE plpgsql;

-- Удаление позиции в заказе

CREATE OR REPLACE function delete_pos_order ( oIdOrder integer, oIdProd integer) RETURNS int

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

51

вход: delete_id - id позиции в заказе, которая будет удалена выход: 1 - БД обновлена, 0 - Ошибка

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

*/ as $$

declare pIdPair int default 0; declare pNum int default 0; begin

select id_pair, num from pos_order where oIdOrder = id_order and oIdProd = id_prod into pIdPair, pNum;

if pIdPair is not null then

update pos_order set num = num-1 where num> pNum and id_order = oIdOrder;

DELETE FROM pos_order WHERE id_pair = pIdPair; return 1;

else

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

return 0; end if;

end $$ LANGUAGE plpgsql;

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

CREATE OR REPLACE function add_shd ( nameOfShd text) RETURNS VOID as $$

declare flag int default 0; begin

if (select id_shd from shd where nameShd = nameOfShd) is not null then

raise exception 'Shd with this names already exists' ;

else

INSERT INTO shd(nameShd) VALUES ($1); end if;

end $$ LANGUAGE plpgsql;

52

--Удаление варианта из shd

CREATE OR REPLACE function delete_shd (

ShdIdToDelete integer) RETURNS VOID

as $$ begin

if(select id_shd from shd where ShdIdToDelete = id_shd) is not null then

DELETE FROM shd WHERE id_shd = ShdIdToDelete;

else

raise exception 'Shd with this id does not exist. DB wasnt

updated.'; end if;

end $$ LANGUAGE plpgsql;

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

CREATE OR REPLACE function add_order (oIdShd integer, oDateReg date) RETURNS VOID

as $$

declare flag int default 0; begin

select id_order from orderr where oIdShd = id_shd and oDateReg = date_reg into flag;

if flag is not null then

raise exception 'Order with this shd and date reg already

exists'; else

INSERT INTO orderr (id_shd, date_reg) VALUES ($1, $2); end if;

end $$ LANGUAGE plpgsql;

--Удаление варианта из ORDERR

CREATE OR REPLACE function delete_order (

OrderIdToDelete integer) RETURNS VOID

as $$

53

begin

if(select id_order from orderr where OrderIdToDelete = id_order) is not null then

DELETE FROM orderr WHERE id_order = OrderIdToDelete;

else

raise exception 'Order with this id does not exist. DB wasnt

updated.'; end if;

end $$ LANGUAGE plpgsql;

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

CREATE OR REPLACE function add_typeParam (nameOfPT text) RETURNS VOID as $$

declare flag int default 0; begin

select id_paramtype from type_param where name_paramtype = nameOfPT into flag;

if flag is not null then

raise exception 'Type with this names already exists';

else

INSERT INTO type_param(name_paramtype) VALUES ($1); end if;

end $$ LANGUAGE plpgsql;

--Удаление варианта из type_param

CREATE OR REPLACE function delete_typeParam (

PTIdToDelete integer) RETURNS VOID

as $$ begin

if(select id_paramtype from type_param where PTIdToDelete = id_paramtype) is not null then

DELETE FROM type_param WHERE PTIdToDelete = id_paramtype;

else

raise exception 'type_param with this id does not exist. DB wasnt updated.';

end if;

54

end $$ LANGUAGE plpgsql;

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

CREATE OR REPLACE function add_parameter (

PNAME text,

PUOM integer, PTYPEPAR integer, pIdEnum integer

)

returns integer as $$

declare vYES int; declare vIdEnum int; declare vIdUOM int; declare oRes int; begin

/*функция: Создание нового параметра вход: PSHNAME - обозначение параметра,

PNAME - имя параметра,

PUOM - единица измерения парметра,

PTYPEPAR - тип параметра (1 - численный, 2 - перечисление, 3 -

агрегат),

pIdEnum - ид. перечисления эффекты:

требования:

1.для типов 1,3 pIdEnum=0,

2. Для типов 2,3 PUOM=0*/ oRes=1;

select count(*) from parameters where name_param = pName into vYes;

if (vYes=0) then

if (pTypePar=1) then vIdEnum=null;

else vIdEnum=pIdEnum; end if;

55

if(pTypePar=2) then vIdUOM = null;

else

vIdUOM = PUOM;

end if;

insert into parameters(name_param,id_uom,id_paramtype,id_enum) values(pName, vIdUOM,pTypePar,vIdEnum);

else oRes=0;

end if; return oRes;

end $$ LANGUAGE plpgsql;

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

CREATE OR REPLACE function delete_param (

PIdToDelete integer) RETURNS VOID

as $$ begin

if(select count(*) from parameters where PIdToDelete = id_param) is not null then

DELETE FROM parameters WHERE PIdToDelete = id_param;

else

raise exception 'parameter with this id does not exist. DB wasnt updated.';

end if;

end $$ LANGUAGE plpgsql;

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

CREATE OR REPLACE function add_class_param (iIdCl int, iIdParam int, max_value int default null, min_value int default null) RETURNS VOID as $$

declare flag int default 0; begin

select id_pair from class_param where iIdCl = id_class and iIdParam = id_param into flag;

if flag is not null then

56

raise exception 'Pair with this ids already exists';

else

INSERT INTO class_param(id_class, id_param, max_value, min_value) VALUES ($1,$2,$3,$4);

end if;

end $$ LANGUAGE plpgsql;

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

CREATE OR REPLACE function delete_class_param (

IdToDelete integer) RETURNS VOID

as $$ begin

if(select id_pair from class_param where IdToDelete = id_pair) is not null then

DELETE FROM class_param WHERE IdToDelete = id_pair;

else

raise exception 'Pair with this id does not exist. DB wasnt

updated.'; end if;

end $$ LANGUAGE plpgsql;

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

CREATE OR REPLACE function add_typeprod_param (iIdProd int, iIdParam int, maxVal int default null, minVal int default null) RETURNS VOID as $$

declare flag int default 0; declare clMaxVal int default 0; declare classProd int default 0; declare clMinVal int default 0; begin

if (select id_variation from product where id_product = iIdProd) = 2 then --Если продукт является типовы, то для него можно добавить параметр

select id_pair from typeprod_param where iIdProd = id_prod and iIdParam = id_param into flag;

if (select id_paramtype from parameters where iIdParam = id_param) = 1 then --Если численный параметр

57

if flag is not null then

raise exception 'Pair with this ids already

exists';

else

select id_class from product where id_product = iIdProd into classProd; --узнаем класс продукта для ограничений параметрра

select max_value from class_param where classProd = id_class and iIdParam = id_param into clMaxVal; --Определяем макс знаения по классу

select min_value from class_param where classProd = id_class and iIdParam = id_param into clMinVal; --Определяем мин знаения по классу

if(clMaxVal<maxval or clMinVal>minval) --Проверка введённых значений по ограниччению класса

then

raise exception 'Max and min values are not correct! Look at table class_param.';

else

INSERT INTO typeprod_param (id_prod, id_param, max_val, min_val) VALUES ($1,$2,$3,$4);

if (select id_pair from prod_param where id_prod = iIdProd and id_param = iIdParam) is null then --Если этого параметра ещё нет

insert into prod_param (id_prod,id_param,id_enum_value,value)values($1,$2,null,null);

end if; end if;

end if;

else

if flag is not null then

raise exception 'Pair with this ids already

exists';

else

INSERT INTO typeprod_param(id_prod, id_param, max_val, min_val) VALUES ($1,$2,null,null); --Границы для перечисления не вставляются

58

if (select id_pair from prod_param where id_prod = iIdProd and id_param = iIdParam) is null then

insert into prod_param (id_prod,id_param,id_enum_value,value)values($1,$2,null,null);

end if;

end if; end if;

else

raise exception 'This produuct is not TypeProduct!'; end if;

end $$ LANGUAGE plpgsql;

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

CREATE OR REPLACE function delete_typeprod_param (

IdToDelete integer) RETURNS VOID

as $$ begin

if(select count(*) from typeprod_param where IdToDelete = id_pair) is not null then

DELETE FROM typeprod_param WHERE IdToDelete = id_pair;

else

raise exception 'Pair with this id does not exist. DB wasnt

updated.'; end if;

end $$ LANGUAGE plpgsql;

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

CREATE OR REPLACE function add_prod_param (iIdProd int, iIdParam int, val double precision, iIdEnumVal int) RETURNS table(ORES integer)

as $$

/*функция: Добавление элементов в таблицу prod_param

вход: iIdProd - ид. продукта iIdParam - ид параметра val - значение численное

iIdEnumVal - ид. значения перечисления выход: 1 - БД обновлена, 0 - Ошибка

59

эффекты: 1. Проверяет подходит ли под ограничения val в таблицах typeprod_param и class_param

2. Проверяет правильность перечисления через соответсвие таблицы параметров

3.Проверяет существование такой же пары параметр-продукт

4.Также запрос с несуществующим значчением перечисления

не пройдет

5. Пропустит параметр с нулевыми значениями

*/

declare flag int default 0; declare vEnumPar int default 0; declare vValEnum int default 0; declare varProd int default 0; declare paramType int default 0; declare classProd int default 0;

declare MinVal double precision default 0; declare MaxVal double precision default 0; declare vTypeProd int default 0;

begin

select id_pair from prod_param where iIdProd = id_prod and iIdParam = id_param into flag;

if flag is not null then

raise notice 'Pair with this ids already exists'; oRes = 0;

return;

else

if (select id_paramType from parameters where id_param = iIdParam limit 1) = 1 then --если параметр является ччисленным

select id_variation from product where id_product = iIdProd into varProd; --узнаем тип продукта для ограничений параметрра

select id_class from product where id_product = iIdProd into classProd; --узнаем класс продукта для ограничений параметрра

--(если это типовой продукт или вариант конфигуации

--, то typeProd = 2 или 3)

if (varProd != 2 and varProd != 3) then

60