登录
首页 >  Golang >  Go问答

如何向 PostgreSQL 插入具有预设值的枚举字段?

来源:stackoverflow

时间:2024-02-17 12:36:24 401浏览 收藏

golang学习网今天将给大家带来《如何向 PostgreSQL 插入具有预设值的枚举字段?》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

如果出现空值,我需要枚举的默认值。 默认情况下,它不起作用。我在创建表时设置了默认值。 如果我在值中传递默认值,则会显示默认值,但我有空数据和枚举数据作为输入。

insert into table(enum_value_1, enum_value_2)
values (?, ?)

目前我是这样经过的

insert into table(enum_value_1, enum_value_2)
values (null, 'enum_value')
enum_value_1 enum_value_2
null enum_value

但我需要这样的数据

enum_value_1 enum_value_2
enum_value_default enum_value

创建表命令

create type enum_candidate_status as enum('attended', 'selected', 'rejected', 'not attended');   

create type enum_rating as enum('1', '2', '3', '4', '5');  
 
create table candidate (
candidate_id serial primary key, 
first_name varchar(100), 
candidate_status enum_candidate_status default 'not attended',
interview_rating enum_rating,
);

正确答案


要管理此操作,您必须使用函数和触发器

注意并执行以下操作。我举了你的例子,以便你能够理解。

第一次create type和table

create type enum_candidate_status as enum('attended', 'selected', 'rejected', 'not attended');
create type enum_rating as enum('1', '2', '3', '4', '5');  
create table candidate ( candidate_id serial primary key,  
                    first_name varchar(100),  
                    candidate_status enum_candidate_status default 'not attended',    
                    interview_rating enum_rating);

那么你必须像下面这样创建函数:

create or replace function force_candidate_status_defaults()
returns trigger
language plpgsql as
$func$
begin
new.candidate_status := 'not attended';
return new;
end
$func$;

最后,您必须创建触发器来控制您的查询,如下所示:

create trigger test_table_before_insert
before insert on candidate
for each row
when (new.candidate_status is null)  -- !
execute function force_candidate_status_defaults();

现在您可以测试查询并享受它

INSERT INTO CANDIDATE(candidate_status, interview_rating) VALUES (NULL, '3') RETURNING *;

好了,本文到此结束,带大家了解了《如何向 PostgreSQL 插入具有预设值的枚举字段?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>