1

I have the following issue.

  1. I will receive input as a text from a webservice to insert into a certain psql table. assume

    create table test ( id serial, myvalues text[])

the recieved input will be: insert into test(myvalues) values ('this,is,an,array');

  1. I want to create a trigger before insert that will be able to convert this string to a text [] and insert it

first Idea that came in my mind was to create a trigger before insert

create function test_convert() returns trigger as $BODY%
 BEGIN
   new.myvalues = string_to_array(new.myvalues,',')
   RETURNS NEW
 END; $BODY$ language plpgsql

but this did not work

3 Answers 3

2

You can use the string_to_array function to convert your string into an string array within your insert query:

INSERT INTO test ( myvalues )
VALUES ( string_to_array( 'this,is,an,array', ',' ) );
Sign up to request clarification or add additional context in comments.

2 Comments

The question was different I meant that the insert command I have from a webservice is an insert as string can I do it from a trigger side?
You can't change the type of a value inside an insert query via a before trigger or any other means. You have to change the initial insert query to pass through the correct type.
0

Suppose you receive text in the following format this is an array and you want to convert it to this,is,an,array then you can use string_to_array('this is an array', ' ') and it will be converted. However if you are receiving comma separated then you can just used it.

1 Comment

Try to insert it will throw an error because the insert is expecting an array
0

Creating the Table Schema Like this,

CREATE TABLE expert (
    id VARCHAR(32) NOT NULL,
    name VARCHAR(36),
    twitter_id VARCHAR(40),
    coin_supported text[],
    start_date TIMESTAMP,
    followers BIGINT,
    PRIMARY KEY (id)
    );

Inserting values like this will help you to insert array,

insert into expert(id, name, twitter_id, coin_supported, start_date, followers) values('9ed1cdf2-564c-423e-b8e2-137eg', 'dev1', 'dev1@twitter', '{"btc","eth"}', current_timestamp, 12);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.