Postgres SELECT where the WHERE is UUID or string

后端 未结 3 1721
误落风尘
误落风尘 2020-12-24 05:01

I have the following simplified table in Postgres:

  • User Model
    • id (UUID)
    • uid (varchar)
    • name (varchar)
相关标签:
3条回答
  • 2020-12-24 05:45

    You could check with a regular expression:

    SELECT *
    FROM user
    WHERE ('jsdfhiureeirh' ~ E'^[[:xdigit:]]{8}-([[:xdigit:]]{4}-){3}[[:xdigit:]]{12}$'
           AND id = 'jsdfhiureeirh')
          OR uid = 'jsdfhiureeirh';
    
    0 讨论(0)
  • 2020-12-24 06:02

    I had originally misunderstood the question. If you want to "safely" try to cast a string to a UUID, you can write a function to catch the invalid_text_representation exception and just return null (modified from an answer to a different question):

    CREATE OR REPLACE FUNCTION uuid_or_null(str text)
    RETURNS uuid AS $$
    BEGIN
      RETURN str::uuid;
    EXCEPTION WHEN invalid_text_representation THEN
      RETURN NULL;
    END;
    $$ LANGUAGE plpgsql;
    

    SELECT uuid_or_null('INVALID') IS NULL will then result in true.

    In other words (given that (true or null) = true),

    SELECT * FROM user
    WHERE id = uuid_or_null('FOOBARBAZ') OR uid = 'FOOBARBAZ';
    

    Original answer:

    Postgres will automatically convert the string to a UUID for you, but you need to use a valid UUID. For example:

    SELECT * FROM user
    WHERE id = '5af75c52-cb8e-44fb-93c8-1d46da518ee6' or uid = 'jsdfhiureeirh';
    

    You can also let Postgres generate UUIDs for you using a DEFAULT clause with the uuid_generate_v4() function by using the uuid-ossp extension:

    CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
    
    CREATE TABLE user (  
       id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
       uid TEXT,
       name TEXT
    );
    
    0 讨论(0)
  • 2020-12-24 06:08

    Found it! Casting the UUID column to ::text stops the error. Not sure about the performance hit but on about 5000 rows I get more than adequate performance.

    SELECT * FROM user
    WHERE id::text = 'jsdfhiureeirh' OR uid = 'jsdfhiureeirh';
    
    SELECT * FROM user
    WHERE id::text = '33bb9554-c616-42e6-a9c6-88d3bba4221c' 
      OR uid = '33bb9554-c616-42e6-a9c6-88d3bba4221c';
    
    0 讨论(0)
提交回复
热议问题