I have created simple custom type:
CREATE TYPE skill_progress AS
(id uuid,
count smallint);
There is column skills
in my table users
of type skill_progress[]
. I need to update count
of element in array skill_progress[]
by specified element id. I need something like this:
UPDATE users SET skills['5a0574cc-66b7-4c89-9950-03a2eea0c701'].count = 10
WHERE nick = 'nick4123';
I have created function that does what i need but i would like to find out if there is an easier way.
CREATE OR REPLACE FUNCTION update_sp
(user_id uuid, skill_id uuid, count smallint) RETURNS integer AS $$
DECLARE
i integer;
up integer;
arr skill_progress[];
BEGIN
SELECT skills INTO arr FROM users WHERE id = user_id;
SELECT array_upper(arr, 1) INTO up;
FOR i IN 1..up
LOOP
IF arr[i].id = skill_id THEN
UPDATE users SET skills[i].count = count WHERE id = user_id;
RETURN 0;
END IF;
END LOOP;
RETURN 1;
END
$$
LANGUAGE plpgsql;
I think if i create a new table, then it will be too much data duplication. For each user that table should contain few records where user id is repeated. Like this:
row_num | user_id | skill_id | count
- - - - - - - - - - - - - - - - - - - - -
1 | 1000 | 100 | 2
1 | 1000 | 101 | 3
1 | 1000 | 102 | 5
. . .
What then is the purpose of custom types?
skill_progress
was a table instead of an array of a custom type. Can you explain why it's necessary to do it that way?