这是indexloc提供的服务,不要输入任何密码
Skip to content

use custom sql function as default without requiring field to be nullable #10489

@ryparker

Description

@ryparker

Is your proposal related to a problem?

I'd like to create a custom SQL function that generates ids in a format such as pc_1Pa04ELJnaZjX5rdwAEd0YMV. Id like to use this as the default value of a id field (type text). Similar to how gen_uuid() can be used for UUID type fields.

The current guidance found in the docs is not ideal. I don't want to set id to null for data integrity reasons.

Describe the solution you'd like

Here's an example. I'd like to generate ids using this nanoid fn: https://github.com/elitan/postgres-nanoid/blob/main/nanoid.sql

I then create another function that uses nanoid and takes 0 args

CREATE OR REPLACE FUNCTION userid()
    RETURNS text
    LANGUAGE plpgsql
    VOLATILE
    PARALLEL SAFE
    AS $$
BEGIN
    RETURN nanoid('user_', 24);
END
$$;

Id then expect userid() to appear in this list of default functions:

CleanShot 2024-08-04 at 16 46 29@2x

Metadata

Metadata

Assignees

No one assigned

    Labels

    k/enhancementNew feature or improve an existing feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions