如何将pg_dump的各种对象解析为自己的文件?像函数,表,视图,索引等

时间:2017-05-27 03:31:22

标签: postgresql parsing pg-dump

我正在尝试将pg_dump文件解析为对象拥有的单个文件,以便更容易开发和维护。

这是一个例子:

--
-- Name: u_id; Type: DEFAULT; Schema: sc_udccockpit; Owner: udccockpit
--

ALTER TABLE ONLY alarmentity
    ADD CONSTRAINT alarmentity_pkey PRIMARY KEY (u_id);


--
-- Name: alarmstring_pkey; Type: CONSTRAINT; Schema: sc_udccockpit; Owner: udccockpit; Tablespace: 
--

ALTER TABLE ONLY alarmentity
    ADD CONSTRAINT alarmentity_f_active_description_id_fkey FOREIGN KEY (f_active_description_id) REFERENCES alarmstring(u_id);


--
-- Name: alarmentity_f_model_description_id_fkey; Type: FK CONSTRAINT; Schema: sc_udccockpit; Owner: udccockpit
--

ALTER TABLE ONLY alarmentity
    ADD CONSTRAINT alarmentity_f_model_description_id_fkey FOREIGN KEY (f_model_description_id) REFERENCES alarmstring(u_id);


--
-- Name: alarmentity_f_module_id_fkey; Type: FK CONSTRAINT; Schema: sc_udccockpit; Owner: udccockpit
--

ALTER TABLE ONLY alarmentity
    ADD CONSTRAINT alarmentity_f_module_id_fkey FOREIGN KEY (f_module_id) REFERENCES alarmstring(u_id);


--
-- Name: alarmentity_f_node_name_id_fkey; Type: FK CONSTRAINT; Schema: sc_udccockpit; Owner: udccockpit
--

ALTER TABLE ONLY alarmentity
    ADD CONSTRAINT alarmentity_f_node_name_id_fkey FOREIGN KEY (f_node_name_id) REFERENCES alarmstring(u_id);


--
-- Name: alarmentity_f_resource_id_id_fkey; Type: FK CONSTRAINT; Schema: sc_udccockpit; Owner: udccockpit
--

ALTER TABLE ONLY alarmentity
    ADD CONSTRAINT alarmentity_f_resource_id_id_fkey FOREIGN KEY (f_resource_id_id) REFERENCES alarmstring(u_id);

我想将其更改为,例如: file:alarmentity_pkey.sql,其中只有

之类的内容
--
-- Name: u_id; Type: DEFAULT; Schema: sc_udccockpit; Owner: udccockpit
--

ALTER TABLE ONLY alarmentity
    ADD CONSTRAINT alarmentity_pkey PRIMARY KEY (u_id);

我认为我想要的是: 从“ALTER TABLE ONLY”开始 以“;”结束 包括“CONSTRAINT”,“PRIMARY” 在“CONSTRAINT”和“PRIMARY”之间提取单词作为文件名。

1 个答案:

答案 0 :(得分:0)

好的,我多次尝试后找到了答案。要解析并获取“仅fkey”单个文件,可以使用'awk'命令。

   function extract_constraint_fkey(){
    awk ' /--/,/\;$/ { str = str ?  str "\n" $0 : $0 } /\;$/ { if( str ~ /FOREIGN KEY/ ) { print str > "database\/constraint\/fkey\/"substr($3,1)".sql" };str = "" };' $1

}

您可以尝试按照此操作继续解析与表格约束相关的主键,索引,更改序列等。

BR //袁元文