0

what is the migration to convert a column template_id of data_type array of string to integer?

Example:

A row has template_id with value ["2"]. I want it to be 2.

All value of template_id has one element in array.

2 Answers 2

2

I'll recommend the following approach to do this

  1. Create a new field temp_template_id with datatype int
  2. Insert all the values of the template_id to the temp_template_id
  3. Remove column template_id
  4. Rename column temp_template_id to template_id

a. rails g migration AddTempTemplateDataToTableName

def change
  add_column :table_name, :temp_template_id, :integer
end

b. rails g migration RenameColumnTemptemplateID

def self.up
  # Script to fill column `temp_template_id` from 'template_id'
  remove_column :table_name, :template_id
  rename_column :table_name, :temp_template_id, :template_id
end

def self.down      
  rename_column :table_name, :template_id, :temp_template_id
  add_column :table_name, :template_id, :array, :default => []
  # Script to fill column `template_id` from 'temp_template_id'
end
Sign up to request clarification or add additional context in comments.

Comments

1

the SQL migration would be as easy as using n[1]:

t=# create table t3(n int[]);
CREATE TABLE
t=# insert into t3 select array[2];
INSERT 0 1
t=# select * from t3;
  n
-----
 {2}
(1 row)

t=# alter table t3 alter COLUMN n type int using n[1];
ALTER TABLE
t=# select * from t3;
 n
---
 2
(1 row)

and in case you had array not as int[], you will need double cast to avoiod

ERROR: result of USING clause for column "template_id" cannot be cast automatically to type integer HINT: You might need to add an explicit cast.

alter table t3 alter COLUMN n type int using n[1]::text::int;

should do the trick, here's example:

t=# create table t3(n text[]);
CREATE TABLE
t=# insert into t3 select array[2];
INSERT 0 1
t=# select * from t3;
  n
-----
 {2}
(1 row)

t=# alter table t3 alter COLUMN n type int using n[1]::text::int;
ALTER TABLE
t=# select * from t3;
 n
---
 2
(1 row)

2 Comments

ERROR: result of USING clause for column "template_id" cannot be cast automatically to type integer HINT: You might need to add an explicit cast. Here template_id is 'n'
try adding ::text::int as in my asnwer

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.