Postgres SELECT where the WHERE is UUID or string

后端 未结 3 1744
误落风尘
误落风尘 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 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
    );
    

提交回复
热议问题