3

I've got two columns in PostgreSQL, hostname and ip. Hostname is the primary key and ip is an array of IPs. I want to be able to insert IPs for a give hostname, on conflict I want to append to the array with the data I'm trying to insert and the output data should be unique.

e.g

hostname - ip

test.com {1.1.1.1,2.2.2.2}

Input

I attempt to insert...

test.com {1.1.1.1, 3.3.3.3, 4.4.4.4}

Output

test.com {1.1.1.1, 2.2.2.2 ,3.3.3.3, 4.4.4.4}

insert into auto_scope_pre_proc (hostname,ip) values ('test.com', '{10.10.10.10, 10.10.10.22}'::inet[])
on conflict (hostname) do update
SET ip = array_append(auto_scope_pre_proc.ip,ip);

1 Answer 1

4

The function array_append does not filter duplicates entries. Here is a possible solution:

drop table auto_scope_pre_proc;
DROP TABLE
create table auto_scope_pre_proc
(
  hostname varchar(20) primary key,
  ip inet[]
);
CREATE TABLE
insert into auto_scope_pre_proc (hostname,ip) values ('test.com', '{1.1.1.1, 2.2.2.2}'::inet[])
on conflict (hostname) do update
set ip = array( select distinct unnest(auto_scope_pre_proc.ip || excluded.ip));
INSERT 0 1
select * from auto_scope_pre_proc;
 hostname |        ip         
----------+-------------------
 test.com | {1.1.1.1,2.2.2.2}
(1 row)

insert into auto_scope_pre_proc (hostname,ip) values ('test.com', '{1.1.1.1, 3.3.3.3, 4.4.4.4}'::inet[])
on conflict (hostname) do update
set ip = array (select distinct unnest(auto_scope_pre_proc.ip || excluded.ip));
INSERT 0 1
select * from auto_scope_pre_proc;
 hostname |                ip                 
----------+-----------------------------------
 test.com | {4.4.4.4,2.2.2.2,3.3.3.3,1.1.1.1}
(1 row)
1
  • I'm having a little trouble with this - for existing columns with a null constraint, even if they have data, the non-null constraint is being triggered. As if I'm trying to make a new row without those values set :-/ Apr 21 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.