![](/img/trans.png)
[英]How to stop Django/PSQL from auto-incrementing table ID on creation failure
[英]Copy from csv into table with id serial column auto-incrementing PSQL
寻找一种解析解决方案,该解决方案将从CSV复制到我的数据库中,并生成最终的序列ID。 要么在后端,要么在复制。 照原样,我的ID在复制后为空。
echo CREATE TABLE IF NOT EXISTS qs_facts_template (id SERIAL NOT NULL, symbol varchar(8), timestamp date, close real null, open real null, high real null, low real null, volume real null, CONSTRAINT qs_facts_template_key PRIMARY KEY (id)) WITH (OIDS=TRUE) TABLESPACE pg_default; ALTER TABLE qs_facts_template OWNER to postgres; | psql -U postgres -h %host% readyloop
echo CREATE TABLE IF NOT EXISTS qs_facts AS select * from qs_facts_template;| psql -U postgres -h %host% readyloop
echo \copy qs_facts (symbol, timestamp, close, open, high, low, volume) from PROGRAM 'cat C:\Users\user\Documents\quantshare\quotes.csv' DELIMITER ';' CSV HEADER| psql -U postgres -h %host% %dbName%
这篇文章: https : //unix.stackexchange.com/questions/277080/copy-csv-data-while-simultanely-filling-serial-column无法解决我的问题。 我使用了Guido提到的命令并使副本起作用,但是id均为null。
我在想也许可以在复制后设置值。
您可以编写一个BEFORE
触发器:
CREATE FUNCTION id_trigger() RETURNS trigger
LANGUAGE plpgsql AS
$$BEGIN
NEW.id = nextval(pg_get_serial_sequence(TG_ARGV[0], 'id'));
RETURN NEW;
END;$$;
CREATE TRIGGER id_trigger BEFORE INSERT ON qs_facts_template
FOR EACH ROW EXECUTE PROCEDURE id_trigger('qs_facts_template');
问题是复制不会复制除列以外的所有内容,这增加了您无法将表更改为串行的事实。
因此,我从原始模板表中将脚本导出到pg4admin中,并能够导出此脚本
echo DROP materialized view if exists mv_qs_facts cascade| psql -U postgres -h %host% %dbName%
echo DROP materialized view if exists mv_qs_symbols cascade| psql -U postgres -h %host% %dbName%
echo DROP TABLE if exists qs_facts cascade| psql -U postgres -h %host% %dbName%
echo drop table if exists qs_facts_template CASCADE;| psql -U postgres -h %host% readyloop
Rem create qs_fact table
echo CREATE TABLE IF NOT EXISTS qs_facts_template (id SERIAL, symbol varchar(8), timestamp date, close real null, open real null, high real null, low real null, volume real null, CONSTRAINT qs_facts_template_key PRIMARY KEY (id)) WITH (OIDS=TRUE) TABLESPACE pg_default; ALTER TABLE qs_facts_template OWNER to postgres; | psql -U postgres -h %host% readyloop
echo CREATE TABLE IF NOT EXISTS qs_facts AS select * from qs_facts_template; | psql -U postgres -h %host% readyloop
echo ALTER TABLE public.qs_facts ADD CONSTRAINT qs_facts_key PRIMARY KEY (id); | psql -U postgres -h %host% readyloop
REM I looked at psqladmin and exported the sequence from qs_facts_template
REM http://www.postgresqltutorial.com/postgresql-serial/
echo CREATE SEQUENCE public.qs_facts_id_seq INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1; ALTER SEQUENCE public.qs_facts_id_seq OWNER TO postgres;| psql -U postgres -h %host% readyloop
echo ALTER TABLE public.qs_facts ALTER COLUMN id SET DEFAULT nextval('qs_facts_id_seq'); | psql -U postgres -h %host% readyloop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.