powered by simpleCommunicator - 2.0.59     © 2025 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / PostgreSQL [игнор отключен] [закрыт для гостей] / Нужна практика с postgresql
4 сообщений из 4, страница 1 из 1
Нужна практика с postgresql
    #39346946
mstdmstd
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Всем привет,
Осваивая postgresql ( 9.4.10 ) пишу админку для небольшого сайта с продуктами, примерно с таким набором таблиц :
attribute
attribute_item
category
product
product_attribute
product_category
product_comment
product_downloadable
product_image
product_tag
tag

Также для формирования прайс листа и для операций CRUD-а я использую sql-функции (ниже).
Ордера пока не делаю.
Интересует ваше мнение о функциях ниже и подскажите, пожалуйста, какие еще задачи можно придумать и поделать для практики
с postgresql ? Можно с использованием расширений sql(jsonb...).



Мои функции ипользуемые для формирования прайс листа и для CRUD-операций:

Код: plsql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
CREATE OR REPLACE FUNCTION public.pd_get_product_prices(
    p_limit integer,
    p_offset integer,
    p_title character varying DEFAULT NULL,
    p_status type_productstatus DEFAULT NULL,
    p_in_stock boolean DEFAULT NULL,
    p_sku character varying DEFAULT NULL,
    p_sale_price_from type_money DEFAULT NULL,
    p_sale_price_till type_money DEFAULT NULL,
    p_rating_from integer DEFAULT NULL,
    p_rating_till integer DEFAULT NULL,
    p_category_list integer[] DEFAULT NULL
)

 RETURNS TABLE(id integer, title character varying, status type_productstatus, sku character varying, user_id smallint, regular_price type_money, sale_price type_money, in_stock boolean, short_description character varying, virtual boolean, rating_count integer, rating_summary integer, rating integer, created_at timestamp without time zone, product_image character varying, product_categories character varying[], product_categories_id smallint[], product_tags character varying[], product_tags_id smallint[], product_attributes jsonb)
 LANGUAGE sql
AS $function$

select * from ( SELECT p.id, p.title, p.status, p.sku, p.user_id, p.regular_price, p.sale_price, p.in_stock, p.short_description, p.virtual, p.rating_count, p.rating_summary,
CAST( floor( p.rating_summary / NULLIF(p.rating_count,0)  ) AS INTEGER ) as rating, p.created_at,
(select pi.image from pd_product_image as pi where pi.product_id = p.id and pi.is_main = true ) as product_image,
( select array_agg(c.name) from pd_category as c, pd_product_category as pd where c.id= pd.category_id and pd.product_id = p.id) as product_categories,
( select array_agg(c.id) from pd_category as c, pd_product_category as pd where c.id= pd.category_id and pd.product_id = p.id) as product_categories_id,
( select array_agg(t.name) from pd_tag as t, pd_product_tag as pt where t.id= pt.tag_id and pt.product_id = p.id) as product_tags,
( select array_agg(t.id) from pd_tag as t, pd_product_tag as pt where t.id= pt.tag_id and pt.product_id = p.id) as product_tags_id,
( select pa.attributes_data from pd_product_attribute as pa where pa.product_id = p.id) as product_attributes


FROM pd_product AS p LEFT JOIN  pd_product_category AS pc ON pc.product_id = p.id
       WHERE
           ( p.status= p_status OR p_status IS NULL ) AND
           ( p.in_stock = p_in_stock OR p_in_stock IS NULL )  AND
           ( p.sku like p_sku OR p_sku IS NULL )  AND
           ( p.title like p_title OR p_title IS NULL ) AND
           ( ( p.sale_price >= p_sale_price_from AND p.sale_price <= p_sale_price_till ) OR ( p_sale_price_from IS NULL OR p_sale_price_till IS null ) ) AND
          ( pc.category_id = ANY (p_category_list) OR p_category_list IS NULL )
) as rows

       WHERE( (   rows.rating >= p_rating_from AND rows.rating <= p_rating_till ) OR ( p_rating_from IS NULL OR p_rating_till IS null ) )

       ORDER BY rows.sale_price asc
       LIMIT p_limit  OFFSET p_offset;

$function$


CREATE OR REPLACE FUNCTION public.pd_delete_product(p_id integer)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
  begin

      DELETE FROM pd_product_attribute where product_id= p_id;

      DELETE FROM pd_product_category where product_id= p_id;

      DELETE FROM pd_product_comment where product_id= p_id;

      DELETE FROM pd_product_downloadable where product_id= p_id;

      DELETE FROM pd_product_image where product_id= p_id;

      DELETE FROM pd_product_tag where product_id= p_id;

      DELETE FROM pd_product where id= p_id;

      RETURN p_id;

  end
$function$



CREATE OR REPLACE FUNCTION public.pd_delete_product(p_id integer)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
  begin

      DELETE FROM pd_product_attribute where product_id= p_id;

      DELETE FROM pd_product_category where product_id= p_id;

      DELETE FROM pd_product_comment where product_id= p_id;

      DELETE FROM pd_product_downloadable where product_id= p_id;

      DELETE FROM pd_product_image where product_id= p_id;

      DELETE FROM pd_product_tag where product_id= p_id;

      DELETE FROM pd_product where id= p_id;

      RETURN p_id;

  end
$function$



CREATE OR REPLACE FUNCTION public.delete_product_comment(p_id integer)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
declare
  r pd_product_comment%rowtype;
  begin

      for r in SELECT id FROM pd_product_comment WHERE parent_product_comment_id = p_id loop
          INSERT INTO pd_d(val) VALUES(  CAST( r.id as varchar(255)  )  );
          PERFORM delete_product_comment(r.id);

      end loop;

      DELETE FROM pd_product_comment where id= p_id;

      RETURN p_id;

  end
$function$



CREATE OR REPLACE FUNCTION public.pd_delete_product(p_id integer)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
  begin

      DELETE FROM pd_product_attribute where product_id= p_id;

      DELETE FROM pd_product_category where product_id= p_id;

      DELETE FROM pd_product_comment where product_id= p_id;

      DELETE FROM pd_product_downloadable where product_id= p_id;

      DELETE FROM pd_product_image where product_id= p_id;

      DELETE FROM pd_product_tag where product_id= p_id;

      DELETE FROM pd_product where id= p_id;

      RETURN p_id;

  end
$function$


Спасибо!
...
Рейтинг: 0 / 0
Нужна практика с postgresql
    #39346982
Lonepsycho
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
mstdmstd,

смотря на очень важную функцию (объявлена аж три раза), можно попрактиковаться с FOREIGN KEY для начала.
...
Рейтинг: 0 / 0
Нужна практика с postgresql
    #39347018
mstdmstd
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Lonepsychomstdmstd,

смотря на очень важную функцию (объявлена аж три раза), можно попрактиковаться с FOREIGN KEY для начала.
Да, с 3м копированием косякнул. Не вижу, а редактировать сообщения тут можно ?
...
Рейтинг: 0 / 0
Нужна практика с postgresql
    #39349189
mstdmstd
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Как отредактировать первоначальный пост я не нашел
Ниже несколько функций без повторов
Буду благодарен за комментарии к ним и за возможные идеи/задачи можно придумать с этими таблицами и поделать на севере для практики
с postgresql ? Можно с использованием расширений sql(jsonb...)
Код: plsql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
CREATE OR REPLACE FUNCTION public.pd_get_product_prices(
    p_limit integer,
    p_offset integer,
    p_title character varying DEFAULT NULL,
    p_status type_productstatus DEFAULT NULL,
    p_in_stock boolean DEFAULT NULL,
    p_sku character varying DEFAULT NULL,
    p_sale_price_from type_money DEFAULT NULL,
    p_sale_price_till type_money DEFAULT NULL,
    p_rating_from integer DEFAULT NULL,
    p_rating_till integer DEFAULT NULL,
    p_category_list integer[] DEFAULT NULL
)

 RETURNS TABLE(id integer, title character varying, status type_productstatus, sku character varying, user_id smallint, regular_price type_money, sale_price type_money, in_stock boolean, short_description character varying, virtual boolean, rating_count integer, rating_summary integer, rating integer, created_at timestamp without time zone, product_image character varying, product_categories character varying[], product_categories_id smallint[], product_tags character varying[], product_tags_id smallint[], product_attributes jsonb)
 LANGUAGE sql
AS $function$

select * from ( SELECT p.id, p.title, p.status, p.sku, p.user_id, p.regular_price, p.sale_price, p.in_stock, p.short_description, p.virtual, p.rating_count, p.rating_summary,
CAST( floor( p.rating_summary / NULLIF(p.rating_count,0)  ) AS INTEGER ) as rating, p.created_at,
(select pi.image from pd_product_image as pi where pi.product_id = p.id and pi.is_main = true ) as product_image,
( select array_agg(c.name) from pd_category as c, pd_product_category as pd where c.id= pd.category_id and pd.product_id = p.id) as product_categories,
( select array_agg(c.id) from pd_category as c, pd_product_category as pd where c.id= pd.category_id and pd.product_id = p.id) as product_categories_id,
( select array_agg(t.name) from pd_tag as t, pd_product_tag as pt where t.id= pt.tag_id and pt.product_id = p.id) as product_tags,
( select array_agg(t.id) from pd_tag as t, pd_product_tag as pt where t.id= pt.tag_id and pt.product_id = p.id) as product_tags_id,
( select pa.attributes_data from pd_product_attribute as pa where pa.product_id = p.id) as product_attributes


FROM pd_product AS p LEFT JOIN  pd_product_category AS pc ON pc.product_id = p.id
       WHERE
           ( p.status= p_status OR p_status IS NULL ) AND
           ( p.in_stock = p_in_stock OR p_in_stock IS NULL )  AND
           ( p.sku like p_sku OR p_sku IS NULL )  AND
           ( p.title like p_title OR p_title IS NULL ) AND
           ( ( p.sale_price >= p_sale_price_from AND p.sale_price <= p_sale_price_till ) OR ( p_sale_price_from IS NULL OR p_sale_price_till IS null ) ) AND
          ( pc.category_id = ANY (p_category_list) OR p_category_list IS NULL )
) as rows

       WHERE( (   rows.rating >= p_rating_from AND rows.rating <= p_rating_till ) OR ( p_rating_from IS NULL OR p_rating_till IS null ) )

       ORDER BY rows.sale_price asc
       LIMIT p_limit  OFFSET p_offset;

$function$


CREATE OR REPLACE FUNCTION public.pd_update_product(p_id integer, p_title character varying, p_status type_productstatus, p_sku character varying, p_user_id integer, p_regular_price type_money, p_sale_price type_money, p_in_stock boolean, p_is_homepage boolean, p_is_featured boolean, p_short_description character varying, p_description text, p_has_attributes boolean, p_downloadable boolean, p_virtual boolean, p_category_list integer[] DEFAULT NULL::integer[], p_tag_list integer[] DEFAULT NULL::integer[], p_attribute_list jsonb DEFAULT NULL::jsonb, p_created_at timestamp without time zone DEFAULT NULL::timestamp without time zone)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
  begin
    IF p_id <= 0 THEN

      INSERT INTO pd_product ( title, status, sku, user_id, regular_price, sale_price, in_stock, is_homepage, is_featured, short_description, description, has_attributes, downloadable, virtual )
        VALUES(  p_title, p_status, p_sku, p_user_id, p_regular_price, p_sale_price, p_in_stock, p_is_homepage, p_is_featured, p_short_description, p_description, p_has_attributes, p_downloadable, p_virtual );
      p_id= lastval();

      IF (p_created_at IS NOT NULL ) THEN
        UPDATE pd_product SET created_at= p_created_at
          where id= p_id;
      END IF;

    ELSE

      UPDATE pd_product set title= p_title, status= p_status, sku= p_sku, user_id= p_user_id, regular_price= p_regular_price, sale_price= p_sale_price, in_stock= p_in_stock, is_homepage= p_is_homepage, is_featured= p_is_featured, short_description= p_short_description, description= p_description, has_attributes= p_has_attributes, downloadable= p_downloadable, virtual= p_virtual, updated_at= now()
        where id= p_id;

        IF p_downloadable = false THEN
          DELETE FROM pd_product_downloadable where product_id= p_id;
        END IF;

        IF p_has_attributes = false THEN
          DELETE FROM pd_product_attribute where product_id= p_id;
        END IF;

    END IF;

    PERFORM pd_update_product_category(p_id, p_category_list);

    PERFORM pd_update_product_tag(p_id, p_tag_list);

    PERFORM pd_update_product_attribute(p_id, p_attribute_list);

    RETURN p_id;

  end
$function$


CREATE OR REPLACE FUNCTION public.pd_delete_product(p_id integer)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
  begin

      DELETE FROM pd_product_attribute where product_id= p_id;

      DELETE FROM pd_product_category where product_id= p_id;

      DELETE FROM pd_product_comment where product_id= p_id;

      DELETE FROM pd_product_downloadable where product_id= p_id;

      DELETE FROM pd_product_image where product_id= p_id;

      DELETE FROM pd_product_tag where product_id= p_id;

      DELETE FROM pd_product where id= p_id;

      RETURN p_id;

  end
$function$



CREATE OR REPLACE FUNCTION public.pd_delete_product_comment(p_id integer)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
declare
  r pd_product_comment%rowtype;
  begin

      for r in SELECT id FROM pd_product_comment WHERE parent_product_comment_id = p_id loop
          -- INSERT INTO pd_d(val) VALUES(  CAST( r.parent_product_comment_id as varchar(255)  )  );
          PERFORM pd_delete_product_comment(r.id);

      end loop;

      DELETE FROM pd_product_comment where id= p_id;

      RETURN p_id;

  end
$function$


CREATE OR REPLACE FUNCTION public.pd_recalc_product_rating(p_id integer, p_write_to_product boolean)
 RETURNS TABLE(comment_rating_count integer, comment_rating_sum integer)
 LANGUAGE plpgsql
AS $function$
DECLARE comment_rating_count integer;
DECLARE comment_rating_sum integer;
   begin

       SELECT count("id"), sum(rating) INTO comment_rating_count, comment_rating_sum FROM pd_product_comment WHERE product_id = p_id LIMIT 1;
       IF ( p_write_to_product ) THEN
          UPDATE pd_product  SET rating_count = comment_rating_count, rating_summary= COALESCE(comment_rating_sum,0) WHERE id = p_id;
       END IF;
       RETURN QUERY SELECT comment_rating_count, COALESCE( comment_rating_sum,0 ) ;

    end
$function$


Спасибо!
...
Рейтинг: 0 / 0
4 сообщений из 4, страница 1 из 1
Форумы / PostgreSQL [игнор отключен] [закрыт для гостей] / Нужна практика с postgresql
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]