Improve update packages views database function

Signed-off-by: Sergio Castaño Arteaga <tegioz@icloud.com>
This commit is contained in:
Sergio Castaño Arteaga 2025-06-23 12:48:33 +02:00
parent 1a8645eab5
commit 1e3b79736a
2 changed files with 26 additions and 7 deletions

View File

@ -6,12 +6,16 @@ returns void as $$
-- Insert or update the corresponding views counters as needed
insert into package_views (package_id, version, day, total)
select
(value->>0)::uuid as package_id,
(value->>1)::text as version,
(value->>2)::date as day,
(value->>3)::integer as total
from jsonb_array_elements(p_data)
select views_batch.*
from (
select
(value->>0)::uuid as package_id,
(value->>1)::text as version,
(value->>2)::date as day,
(value->>3)::integer as total
from jsonb_array_elements(p_data)
) as views_batch
join snapshot s on s.package_id = views_batch.package_id and s.version = views_batch.version
on conflict (package_id, version, day) do
update set total = package_views.total + excluded.total;
$$ language sql;

View File

@ -1,6 +1,6 @@
-- Start transaction and plan tests
begin;
select plan(3);
select plan(4);
-- Declare some variables
\set lockKey 1
@ -96,6 +96,21 @@ select results_eq(
$$,
'Third run: one update and four inserts'
);
select update_packages_views(:lockKey, '[
["00000000-0000-0000-0000-000000000001", "2.0.0", "2021-12-5", 10],
["00000000-0000-0000-0000-000000000003", "1.0.0", "2021-12-6", 5]
]');
select results_eq(
'select * from package_views',
$$ values
('00000000-0000-0000-0000-000000000001'::uuid, '1.0.0', '2021-12-3'::date, 20),
('00000000-0000-0000-0000-000000000001'::uuid, '1.0.0', '2021-12-5'::date, 10),
('00000000-0000-0000-0000-000000000001'::uuid, '1.0.1', '2021-12-5'::date, 10),
('00000000-0000-0000-0000-000000000002'::uuid, '1.0.0', '2021-12-5'::date, 10),
('00000000-0000-0000-0000-000000000002'::uuid, '1.0.0', '2021-12-6'::date, 5)
$$,
'Fourth run: some invalid views that will be ignored, no changes'
);
-- Finish tests and rollback transaction
select * from finish();