users.sql 1.0 KB

12345678910111213141516171819202122232425262728
  1. CREATE EXTENSION IF NOT EXISTS pgcrypto;
  2. -- UUID v7: 48-bit ms timestamp | 4-bit version (0111) | 12-bit random | 2-bit variant (10) | 62-bit random
  3. CREATE OR REPLACE FUNCTION gen_uuid_v7()
  4. RETURNS uuid
  5. LANGUAGE plpgsql
  6. AS $$
  7. DECLARE
  8. unix_ms bigint;
  9. uuid_bytes bytea;
  10. BEGIN
  11. unix_ms := (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint;
  12. uuid_bytes := gen_random_bytes(16);
  13. uuid_bytes := overlay(uuid_bytes PLACING substring(int8send(unix_ms) FROM 3) FROM 1 FOR 6);
  14. uuid_bytes := set_byte(uuid_bytes, 6, (get_byte(uuid_bytes, 6) & x'0f'::int) | x'70'::int);
  15. uuid_bytes := set_byte(uuid_bytes, 8, (get_byte(uuid_bytes, 8) & x'3f'::int) | x'80'::int);
  16. RETURN encode(uuid_bytes, 'hex')::uuid;
  17. END;
  18. $$;
  19. CREATE TABLE users (
  20. id UUID PRIMARY KEY DEFAULT gen_uuid_v7(),
  21. uuid_key UUID NOT NULL DEFAULT gen_random_uuid(),
  22. email TEXT NOT NULL UNIQUE,
  23. name TEXT NOT NULL,
  24. created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  25. pass_hash TEXT NOT NULL
  26. );