-- Name-derived identity IDs used to carry a 5-character third group and an -- unmasked variant nibble. The current form drops the extra character and -- clears bit 2 of the variant nibble; this rewrites every stored copy. -- +goose Up -- +goose StatementBegin CREATE FUNCTION fix_stable_ids(s text) RETURNS text LANGUAGE plpgsql AS $$ DECLARE m text[]; BEGIN LOOP m := regexp_match(s, '(([0-9a-f]{8}-[0-9a-f]{4}-5)[0-9a-f]([0-9a-f]{3}-)([89a-f])([0-9a-f]{3}-[0-9a-f]{12}))'); EXIT WHEN m IS NULL; s := replace(s, m[1], m[2] || m[3] || translate(m[4], 'cdef', '89ab') || m[5]); END LOOP; RETURN s; END $$; -- +goose StatementEnd -- +goose StatementBegin DO $$ DECLARE pat constant text := '[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{4}-[89a-f][0-9a-f]{3}-[0-9a-f]{12}'; c record; BEGIN -- Referencing rows need the new identity to exist before they move to it. INSERT INTO identities (id, kind, display_name, lifecycle, version, created_at, updated_at) SELECT fix_stable_ids(id), kind, display_name, lifecycle, version, created_at, updated_at FROM identities WHERE id ~ pat; FOR c IN SELECT col.table_name, col.column_name, col.data_type FROM information_schema.columns col JOIN information_schema.tables t USING (table_schema, table_name) WHERE col.table_schema = current_schema() AND t.table_type = 'BASE TABLE' AND col.data_type IN ('text', 'character varying', 'json', 'jsonb', 'bytea') AND col.is_generated = 'NEVER' AND NOT (col.table_name = 'identities' AND col.column_name = 'id') AND col.table_name NOT LIKE 'goose%' LOOP IF c.data_type = 'bytea' THEN -- Only the resource documents are text; other bytea is binary. CONTINUE WHEN c.table_name NOT IN ('resources', 'resource_history'); EXECUTE format('UPDATE %I SET %I = convert_to(fix_stable_ids(convert_from(%I, ''UTF8'')), ''UTF8'') WHERE convert_from(%I, ''UTF8'') ~ %L', c.table_name, c.column_name, c.column_name, c.column_name, pat); ELSIF c.data_type IN ('json', 'jsonb') THEN EXECUTE format('UPDATE %I SET %I = fix_stable_ids(%I::text)::%s WHERE %I::text ~ %L', c.table_name, c.column_name, c.column_name, c.data_type, c.column_name, pat); ELSE EXECUTE format('UPDATE %I SET %I = fix_stable_ids(%I) WHERE %I ~ %L', c.table_name, c.column_name, c.column_name, c.column_name, pat); END IF; END LOOP; DELETE FROM identities WHERE id ~ pat; END $$; -- +goose StatementEnd DROP FUNCTION fix_stable_ids(text); -- +goose Down SELECT 1;