Files
gochat/backend/migrations/000070_decode_shangwutong_contact_attributes.up.sql
T

75 lines
3.1 KiB
PL/PgSQL

CREATE OR REPLACE FUNCTION gochat_percent_decode(value TEXT)
RETURNS TEXT
LANGUAGE plpgsql
IMMUTABLE
STRICT
AS $$
DECLARE
position INTEGER := 1;
encoded_bytes TEXT := '';
token TEXT;
BEGIN
WHILE position <= char_length(value) LOOP
token := substr(value, position, 1);
IF token = '%' AND substr(value, position + 1, 2) ~ '^[0-9A-Fa-f]{2}$' THEN
encoded_bytes := encoded_bytes || substr(value, position + 1, 2);
position := position + 3;
ELSIF token = '+' THEN
encoded_bytes := encoded_bytes || '20';
position := position + 1;
ELSE
encoded_bytes := encoded_bytes || encode(convert_to(token, 'UTF8'), 'hex');
position := position + 1;
END IF;
END LOOP;
RETURN convert_from(decode(encoded_bytes, 'hex'), 'UTF8');
EXCEPTION WHEN OTHERS THEN
RETURN value;
END;
$$;
UPDATE contacts
SET
custom_attributes = COALESCE(custom_attributes, '{}'::jsonb)
|| jsonb_strip_nulls(jsonb_build_object(
'swt_ip_location', gochat_percent_decode(custom_attributes->>'swt_ip_location'),
'swt_color_depth', gochat_percent_decode(custom_attributes->>'swt_color_depth'),
'swt_resolution', gochat_percent_decode(custom_attributes->>'swt_resolution'),
'swt_os', gochat_percent_decode(custom_attributes->>'swt_os'),
'city', CASE
WHEN COALESCE(custom_attributes->>'city', '') = ''
THEN gochat_percent_decode(custom_attributes->>'swt_ip_location')
END
)),
additional_attributes = COALESCE(additional_attributes, '{}'::jsonb)
|| jsonb_strip_nulls(jsonb_build_object(
'swt_ip_location', gochat_percent_decode(additional_attributes->>'swt_ip_location'),
'swt_color_depth', gochat_percent_decode(additional_attributes->>'swt_color_depth'),
'swt_resolution', gochat_percent_decode(additional_attributes->>'swt_resolution'),
'swt_os', gochat_percent_decode(additional_attributes->>'swt_os'),
'city', CASE
WHEN COALESCE(additional_attributes->>'city', '') = ''
THEN gochat_percent_decode(additional_attributes->>'swt_ip_location')
END
)),
updated_at = CURRENT_TIMESTAMP
WHERE EXISTS (
SELECT 1
FROM contact_inboxes
JOIN inboxes ON inboxes.id = contact_inboxes.inbox_id
WHERE contact_inboxes.contact_id = contacts.id
AND inboxes.channel_type = 'shangwutong'
)
AND (
COALESCE(custom_attributes->>'swt_ip_location', '') ~ '%[0-9A-Fa-f]{2}'
OR COALESCE(custom_attributes->>'swt_color_depth', '') ~ '%[0-9A-Fa-f]{2}'
OR COALESCE(custom_attributes->>'swt_resolution', '') ~ '%[0-9A-Fa-f]{2}'
OR COALESCE(custom_attributes->>'swt_os', '') ~ '%[0-9A-Fa-f]{2}'
OR COALESCE(additional_attributes->>'swt_ip_location', '') ~ '%[0-9A-Fa-f]{2}'
OR COALESCE(additional_attributes->>'swt_color_depth', '') ~ '%[0-9A-Fa-f]{2}'
OR COALESCE(additional_attributes->>'swt_resolution', '') ~ '%[0-9A-Fa-f]{2}'
OR COALESCE(additional_attributes->>'swt_os', '') ~ '%[0-9A-Fa-f]{2}'
);
DROP FUNCTION gochat_percent_decode(TEXT);