gempir

Untitled

Oct 21st, 2024
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. CREATE OR REPLACE FUNCTION old_to_new(old_id TEXT)
  2. RETURNS TEXT AS $$
  3. DECLARE
  4. number NUMERIC;
  5. timestamp_seconds NUMERIC;
  6. timestamp_milliseconds NUMERIC;
  7. random NUMERIC;
  8. new_number NUMERIC;
  9. ulid TEXT;
  10. BEGIN
  11. -- Convert hexadecimal to numeric
  12. number := ('x' || old_id)::bit(128)::numeric;
  13.  
  14. -- Shift by 8 bytes to get the timestamp in seconds
  15. timestamp_seconds := number >> 64;
  16. timestamp_milliseconds := timestamp_seconds * 1000;
  17.  
  18. -- The first 8 bytes are treated as the random part of the ULID
  19. random := number & ((1::numeric << 64) - 1);
  20.  
  21. -- Shift the timestamp by 80 bits to make room for the random part
  22. new_number := (timestamp_milliseconds << 80) | random;
  23.  
  24. -- Convert to base32 encoding (simplified version, might need adjustment)
  25. ulid := encode(new_number::bytea, 'base64');
  26.  
  27. RETURN ulid;
  28. END;
  29. $$ LANGUAGE plpgsql;
Add Comment
Please, Sign In to add comment